1

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!

1
  • 1
    Be careful with 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. Commented May 10, 2013 at 1:50

3 Answers 3

8

Seems you've answered your own first question.


As for the second question, you'll need another Array to maintain a sort order of the map keys.

var mapKeys = Object.keys(myMap);

mapKeys.sort(function(a,b){return myMap[b].length - myMap[a].length});

Then you can iterate the mapKeys to obtain the collections in your sorted order.

mapKeys.forEach(function(key) {
    console.log("Processing ", key);
    var indices = myMap[key];
});
Sign up to request clarification or add additional context in comments.

Comments

3

1) Yes, push would work (as would unshift or splice).

2) Object keys are inherently unordered and as such they do not have a sort function :-) You could add a function to your map to return the values in sorted order however:

myMap.sort = function sortMap(sortFunc) {
    var results = [];
    for (key in this) {
        if (this.hasOwnProperty(key) && this[key] !== sortMap) {
            results.push(this[key]);
        }
    }
    return results.sort(sortFunc);
};

myMap.sort(function(a, b) { return a.length - b.length; });

Some notes:

  • Don't use Array or new Array unless you need to (e. g. Array(12).join("-") to create a string of 11 dashes). Instead use the array literal syntax []. It's clearer (and in most browsers actually faster).
  • When in doubt, open up MDN and the console in your browser and try it out.

Comments

1

How would I sort the map so that the keys are ordered by the number of items in their arrays?

Maps are not ordered — there is no difference between { 'cats': [1,4,5], 'dogs': [2,3,6] } and { 'dogs': [2,3,6], 'cats': [1,4,5] }.

As for the rest of your question — yes, that's all correct. But instead of writing this:

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  

I'd recommend writing this:

var myMap = {
    'cats': [1,4,5], //animals 1,4,5 are cats
    'dogs': [2,3,6]  //animals 2,3,6 are dogs  
};

or perhaps this:

var animals = [ 'cats', 'dogs', 'dogs', 'cats', 'cats', 'dogs' ];

12 Comments

there is a difference between the pair of objects you first mentioned. jsfiddle.net/martco/dvdHq/1
@MartinCortez - yes, but that's because they are different objects not because their keys are in different source order ;-) jsfiddle.net/dvdHq/2
@SeanVieira i'm not questioning why they're different. i'm just pointing out that it's wrong to say that there is no difference.
@MartinCortez: That makes no sense. You must realize that {} === {} also evaluates to false (because each occurrence of {} instantiates a new object); would you therefore insist that there is a difference between {} and {}?
i'm not insisting anything besides that it's wrong to say there is no difference, as you did above
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.