Javascript 如何按javascript中的每个元素计算数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12749200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count array elements by each element in javascript
提问by suresh.g
Possible Duplicate:
How to count Matching values in Array of Javascript
可能的重复:
如何计算 Javascript 数组中的匹配值
I have array with elements as,
我有元素的数组,
array_elements = ["2","1","2","2","3","4","3","3","3","5"];
array_elements = ["2","1","2","2","3","4","3","3","3","5"];
i want to count array elements like following manner,
我想按照以下方式计算数组元素,
Answer:
回答:
2 comes --> 3 times
1 comes --> 1 times
3 comes --> 4 times
4 comes --> 1 times
5 comes --> 1 times
2次--> 3次
1次--> 1次
3次--> 4次
4次--> 1次
5次--> 1次
Note : Each value count should print only once.
注意:每个值计数应该只打印一次。
回答by I Hate Lazy
var counts = {};
for (var i = 0; i < array.length; i++)
counts[array[i]] = (counts[array[i]] + 1) || 1;
console.log(counts);
This assumes a toStringrepresentation of the items in the Array will be acceptable. For example, it will see 1as being the same as "1".
这假设toStringArray 中项目的表示是可以接受的。例如,它将1被视为与"1".
Given your example Array, this will not be an issue.
鉴于您的示例数组,这将不是问题。
回答by Guffa
You can sort the elements and loop through them:
您可以对元素进行排序并遍历它们:
array_elements = ["2", "1", "2", "2", "3", "4", "3", "3", "3", "5"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
回答by xdazz
var array_elements = ["2","1","2","2","3","4","3","3","3","5"];
var result = array_elements.reduce(function(p, c){
if (c in p) {
p[c]++;
} else {
p[c]=1;
}
return p;
}, {});
?console.log(result);?
note: reduce need a shim for old browsers.
注意:减少旧浏览器需要垫片。
回答by prashanth
var arr = ["2","1","2","2","3","4","3","3","3","5"];
var k = {};
//push into hashtable
for(i in arr){
k[arr[i]]=(k[arr[i]]||0)+1; //increments count if element already exists
}
//result
for(var j in k) {
console.log(j+" comes -> "+k[j]+" times");
}

