Search code examples
javascriptoptimization

How do you determine the number of defined elements in an array?


If I have an array in Javascript that has been filled sporadically, how do I determine the number of non-nothing elements in the array?

for example:

var zipCodes = [];
zipCodes[10006] = 'New York, NY';
zipCodes[90210] = 'Los Angeles, CA';

zipCodes.length returns 90,211 here and I really don't want to loop through 90,209 nothings to find out I have two valid elements. Using a for-in loop means dealing with anything that might bubble up the prototype chain and trying to figure out if it's part of this array.

Is there any way, given the array defined above, I can extract "2" as the number of defined elements?


Solution

  • You would need an object with key-value pairs (kind of like an associative array / hashtable) instead of an array:

    var zipCodes = {};
    zipCodes[10006] = 'New York, NY';
    zipCodes[90210] = 'Los Angeles, CA';
    
    
    for(var zipCode in zipCodes) {
        if(zipCodes.hasOwnProperty(zipCode)) {//makes sure prototypes aren't taken into account
    
        }
    }
    

    edit: or you can store objects in an array like this:

    var zipCodes = [];
    zipCodes.push({10006:'New York, NY'});
    zipCodes.push({90210: 'Los Angeles, CA'});
    

    //zipCodes.length = 2