我的数组元素为
array_elements = [“2”,“1”,“2”,“2”,“3”,“4”,“3”,“3”,“3”,“5”];
我想按照以下方式计算数组元素,
答案:
2来了 - > 3次
1来了 - > 1次
3来了 - > 4次
4来了 - > 1次
5来了 - > 1次
注意:每个值计数只能打印一次。
答案 0 :(得分:19)
var counts = {};
for (var i = 0; i < array.length; i++)
counts[array[i]] = (counts[array[i]] + 1) || 1;
console.log(counts);
这假定数组中项目的toString
表示是可接受的。例如,它会将1
视为与"1"
相同。
鉴于你的示例数组,这不会是一个问题。
答案 1 :(得分:10)
您可以对元素进行排序并循环遍历它们:
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');
}
答案 2 :(得分:4)
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);
的 The live demo. 强> 的
注意:减少需要旧浏览器的垫片。
答案 3 :(得分:2)
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");
}