如何在javascript中按每个元素计算数组元素

时间:2012-10-05 15:15:45

标签: javascript

  

可能重复:
  How to count Matching values in Array of Javascript

我的数组元素为

array_elements = [“2”,“1”,“2”,“2”,“3”,“4”,“3”,“3”,“3”,“5”];

我想按照以下方式计算数组元素,

答案:

2来了 - > 3次
 1来了 - > 1次
 3来了 - > 4次
 4来了 - > 1次
 5来了 - > 1次

注意:每个值计数只能打印一次。

4 个答案:

答案 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');
}

演示:http://jsfiddle.net/Guffa/aQsuP/

答案 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");
}