JavaScript: Map-Like Array, Sorting and Adding -


i'm trying create map or dictionary style data structure in javascript. each string key points array of int, , i'd few simple things arrays keys point to.

i have bunch of animals, each id (1,2,3,...). want put these in map know 1,4,5 cats , 2,3,6 dogs.

here's have code explain better.

var mymap = {}; mymap["cats"] = new array(1,4,5);   //animals 1,4,5 cats mymap["dogs"] = new array(2,3,6);   //animals 2,3,6 dogs   

1) how add array? example, if animal #7 cat, following code correct?

mymap["cats"].push(7);   //so mymap["cats"] array [1,4,5,7] 

2) how sort map keys ordered number of items in arrays? in case, mymap["cats"] in front of mymap["dogs"] because array "cats" has more items array "dogs". following code correct?

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

if there's more efficient way in javascript, please let me know. thank much!

seems you've answered own first question.


as second question, you'll need array maintain sort order of map keys.

var mapkeys = object.keys(mymap);  mapkeys.sort(function(a,b){return mymap[b].length - mymap[a].length}); 

then can iterate mapkeys obtain collections in sorted order.

mapkeys.foreach(function(key) {     console.log("processing ", key);     var indices = mymap[key]; }); 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -