JavaScript的:地图状阵列,排序和添加 [英] JavaScript: Map-Like Array, Sorting and Adding

查看:159
本文介绍了JavaScript的:地图状阵列,排序和添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript创建一个映射或字典式的数据结构。每个字符串关键点,一个int数组,我想要做一些简单的事情与键指向数组。

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.

我有一堆的动物,每一个ID(1,2,3,...)。我希望把这些地图中,所以我知道,1,4,5是猫和2,3,6是狗。

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.

下面是我有code解释它更好的。

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)如何将添加的东西到一个数组?例如,如果动物#7是一只猫,将下面的code是正确的?

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)如何将我的地图进行排序,以便该密钥是由他们的阵列中的项目数排序?在这种情况下,MYMAP [猫]将在MYMAP前面[犬],因为猫所述阵列具有比该阵列为「狗」的更多的项目。将以下code是正确的?

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

如果有一个更有效的方式在JavaScript中做到这一点,请让我知道。太谢谢你了!

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


然后就可以遍历映射键来获得你的有序集合。

mapKeys.forEach(function(key) {
    console.log("Processing ", key);
    var indices = myMap[key];
});

这篇关于JavaScript的:地图状阵列,排序和添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆