A Difference Between JavaScript Arrays and Associative Arrays

I’ve been crunching a large government dataset for a project I’m working on. I had to key an array with the ids of some of the data. However, I noticed when I tried to stringify my array, it produced a ton of null values. It took me a second to realize this:

// an associative array in javascript is really just an object
var assoc = {};
// a numerical array is an object with an array constructor
var keyed = [];

// generate some random items for an array
for(var i = 0; i < 1000; i++) {
  var rand = Math.floor(Math.random() * 10000 + 1);
  assoc[rand] = rand;
  keyed[rand] = rand;
}

// count the number of items in the assoc array
var count = 0;
for(var name in assoc) {
  count++;
}

// log them out so we can see the difference
console.log("assoc length = " + count);
console.log("keyed.length = " + keyed.length);

See the Pen eNBNpz by Mike Newell (@newshorts) on CodePen.

 

 

You can see from the above you cannot key a javascript array with random values without the array constructor putting in the missing keys as null. Basically, this makes sense if you look at how arrays are stored in memory, it would be mayhem if you tried to store random keys. So in some cases, you’re better off using a javascript object in literal fashion and key it like you would the array. This way you only need to parse the items stored and not the missing keys.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.