简体   繁体   中英

JavaScript: Map-Like Array, Sorting and Adding

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!

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];
});

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 (eg 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.

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' ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM