0

I need to sort through a data set which as you can see I've assigned to the records variable. From that data I need to see if the zip code exists. If the zip code does not exist then I need to move it into the array (There of course will be duplicates) and continue checking the rest of the records, if it does exist I need to do nothing.

// Declare Array
var numbersArray = [];

// Variables
var records;
var zipCode;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;

output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();

output.innerHTML = "The unique zip codes are: ";

while (records.readNextRecord()) {

    zipCode = records.getSampleZipCode();

    for (index = 0; index < numbersArray.length; index++) {
        if (zipCode === numbersArray[index]) {
            var uniqueZip = false;
            break;
            records++;
        }

        if (zipCode !== numbersArray[index]) {
            numbersArray.push(zipCode);
        }
    }
    output.innerHTML += numbersArray;
}

}

TheStandardRGB
  • 209
  • 2
  • 3
  • 8
  • `numbersArray` is empty when the for loop executes, as far as I can see. Therefore, `index < numbersArray.length` always evaluates `false`. – Stephen Dec 15 '10 at 22:56

2 Answers2

4

You can simplify your for loop like so:

 matchedZip = false;

 for(i in numbersArray) {
    if (numbersArray[i] === zipCode) {
       matchedZip = true;
    }
 }

 if ( ! matchedZip) {
    numbersArray.push(zipCode);
 }

Try plugging that into your while loop. If you have the array push inside of the for loop you're going to end up pushing each zip code in every time there is not a match.

benastan
  • 2,268
  • 15
  • 14
  • Thanks this worked perfectly with a bit of modification to suit my needs. – TheStandardRGB Dec 15 '10 at 23:13
  • `for-in` is not for looping through arrays. More: [*For each over array in JavaScript?*](http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – T.J. Crowder Apr 13 '17 at 05:17
0

Well, you didn't exactly ask a question, but I'll answer anyway :) The answer is that you should not use a normal array for this, but rather a map or associative array. Fortunately a plain Javascript object can be used for this:

var numbers = {};

// Variables
var records;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;

output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();

output.innerHTML = "The unique zip codes are: ";

while (records.readNextRecord()) {

    var zipCode = records.getSampleZipCode();
    numbers[zipCode] = 1; // just picking an arbitrary value
}

for (var zipCode: numbers) {
  output.innerHTML += zip + " ";
}

The reason is that this way you don't need to loop through the existing data for each new input.

Dan
  • 10,990
  • 7
  • 51
  • 80