I'm trying to create a map or dictionary style data structure in JavaScript. Each string key points to an array of int, and I'd like to do a few simple things with the arrays that the keys point to.
I have a bunch of animals, each with an ID (1,2,3,...). I want to put these in a map so I know that 1,4,5 are cats and that 2,3,6 are dogs.
Here's what I have for code to explain it better.
var myMap = {};
myMap["cats"] = new Array(1,4,5); //animals 1,4,5 are cats
myMap["dogs"] = new Array(2,3,6); //animals 2,3,6 are dogs
1) How would I add something to an array? For example, if animal #7 is a cat, would the following code be correct?
myMap["cats"].push(7); //so that myMap["cats"] is now an array with [1,4,5,7]
2) How would I sort the map so that the keys are ordered by the number of items in their arrays? In this case, myMap["cats"] would be in front of myMap["dogs"] because the array for "cats" has more items than the array for "dogs". Would the following code be correct?
myMap.sort(function(a,b){return myMap[b].length - myMap[a].length});
If there's a much more efficient way to do this in JavaScript, please let me know. Thank you so much!
new Array();: if you pass a single number to it, it will initialize an array with that length, not an array with that number inside. Using array literals such as[1,4,5]is preferred.