Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Javascript: Push values to a global array and use it later

Hi All,

Im using AJAX to get data from my xml feed with long list of zipcodes. Since there are some undefined zipcodes in my list I had to add a if else statement.

So I managed to add all zipcodes to my div. But now comes the complex part. I want to filter by range (1000-1900).

I just cant figure out how, since I cant push the zipcodes to a global array which I can use in other functions. Also, my zipcodes are strings at the moment. Now sure how to convert to numbers.

Here is my code:

<div class="container">
    <button type="button" onclick="loadDoc()">Alle Postcodes</button>
    <button type="button" onclick="">Provincie Utrecht</button>
        <br>
    <button id ="filter" class="filterBtn hide-filter" onclick="filter()">Filter</button>   
    <br><br>
    <div class="loader hide-loader" id="loader"></div>    
    <div id="zips"></div>
</div>
<script>

function loadDoc() {
$('#loader').removeClass("hide-loader");    
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xhttp.open("GET", "zipcode-aug.xml", true);
  xhttp.send();    
}

    function myFunction(xml) { 
     $('#loader').addClass("hide-loader");    
     $('#filter').removeClass("hide-filter");    
  var i;
  var xmlDoc = xml.responseXML;
  var table="";
  var x = xmlDoc.getElementsByTagName("vacancy"); 
  for (i = 0; i <x.length; i++) { 
 if (x[i].getElementsByTagName("zipcode")[0].childNodes[0]) {
    var postcodes = x[i].getElementsByTagName("zipcode")[0].childNodes[0].nodeValue;
    var postcodeSlice = postcodes.slice(0,-2);
    var postcodeArray = [];
    postcodeArray.push(postcodeSlice); 
    document.getElementById("zips").innerHTML += postcodeArray[0] + "<br>";
 }      
    else {   
    document.getElementById("zips").innerHTML += ''; 
   }
  }    
}

function filter(){
    console.log(postcodeArray);
}

My first question on threehouse :) Thanks in advance!

Rich Donnellan
Rich Donnellan
Treehouse Moderator 27,741 Points

Question updated with code formatting. Check out the Markdown Cheatsheet link below the "Add an Answer" for syntax examples.

3 Answers

Hi Edwin,

I just wanted to first say that my answer is my opinion and people could have a totally different solution :).

First, I would start by making your code more modular. What I mean is, maybe take so of the work that you do in the loop and make it a function. I will let you decide how to do that.

Second, the Array object has the filter and map method. Have you seen them? If not, google "Array map JS" and "Array filter JS". Learn how to use it, I will give you a quick example below.

const strArray = ["1", "2", "3", "4", "5", "6"];

const numArray = strArray.map(function(item) {
  return parseInt(item);
});

// At this point, numArray has all the values as numbers

const filteredArray = numArray.filter(function(item) {
  return item > 3;
});

console.log(filteredArray);  // Should print [4, 5, 6]

Something else to think about is that the parseInt function will return 234 when you pass a zip code like this: 00234.

Hopefully this helps, -Dan

Hi Daniel,

Thanks for your response. I can work with this :-)!

Rich Donnellan
Rich Donnellan
Treehouse Moderator 27,741 Points

Post your refactored code when you're done. I'd love to see how you handled this.

Hi Rich,

I managed to figure it out :) I bet my code can be more modular and readable. This will be my next task. Atleast it works and I had a little bit of time pressure to fix it.

What I needed was a simple 'tool' that read our XML file with all jobopenings (4k of openings) and I needed the tool to filter out every information except the zipcodes and placenames and remove the duplicates. Which I can copy and paste into Facebook Ad manager to bulk target on location.

Also needed a filter by the 12 provinces with each different zipcode ranges.

<button class ="zipbtn" id="utrecht" type="button" data-postcoderanges='[
{"min":1390, "max":1393}, 
{"min":1396, "max":1396},
{"min":1426, "max":1427},
{"min":3382, "max":3464},
{"min":3467, "max":3769},
{"min":3795, "max":3836},
{"min":3900, "max":3924},
{"min":3926, "max":3999},
{"min":4120, "max":4125},
{"min":4130, "max":4139}   
]' onclick="loadDoc()">Utrecht</button>  

Script:

var mincodes;
var maxcodes;
var ids;

$(".zipbtn").click(function() {
    ids = this.id; 
});

$(".zipbtn").click(function() {  
    var minpostcode = $('#' + ids).data('postcoderanges');
    mincodes = minpostcode.map(a => a.min);
    maxcodes = minpostcode.map(a => a.max);
});

//POSTCODE FUNCTION 
function loadDoc() {
$('#loader').removeClass("hide-loader");    
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xhttp.open("GET", "vacatures.xml", true);
  xhttp.send();    
}

function myFunction(xml) { 
    $('#loader').addClass("hide-loader");    
    $('.removeClass').removeClass("removeClass");        
  var i;
  let plcs = []; 
  var xmlDoc = xml.responseXML;  
  var x = xmlDoc.getElementsByTagName("vacancy");
  for (i = 0; i <x.length; i++) { 
     if (x[i].getElementsByTagName("zipcode")[0].childNodes[0]) {
        var postcodes = x[i].getElementsByTagName("zipcode")[0].childNodes[0].nodeValue;
        var postcodeSlice = postcodes.slice(0,-2);
        let postcodeArray = [];
        postcodeArray.push(postcodeSlice);
        let postcodeFilter = [];
         for(let v = 0; v < postcodeArray.length; v++) {
             for (let x = 0; x < mincodes.length; x++) {
                for (let j = 0; j < maxcodes.length; j++) {
                    if ((postcodeArray[v] >= mincodes[x]) && (postcodeArray[v]) <= maxcodes[x]) {
                        postcodeFilter.push(postcodeArray[v]);
                        let counterLength = $('#zips').text().length; 
                        let totalzips = counterLength / 6;
                        document.getElementById("counter").innerHTML = totalzips + " postcodes";

                    }
                }
            }
        }
            if ( postcodeFilter[0] ) {
            document.getElementById("zips").innerHTML += postcodeFilter[0] + ", ";
            plcs.push(postcodeFilter[0]);
            var placesNames = x[i].getElementsByTagName("location")[0].childNodes[0].nodeValue;
            document.getElementById("allplaces").innerHTML += placesNames + ", "; 
        }   else {
            document.getElementById("zips").innerHTML += ''; 
        }
    }      
        else {   
        document.getElementById("zips").innerHTML += ''; 
        }
      }  

    }

One of my first real scripts (normally copy/paste most of js and do some tweaking) so im happy that it worked :)