如何计算变量在javascript数组中重复的次数?

时间:2012-07-09 07:22:18

标签: javascript arrays sorting loops

如何获取阵列成员及其重复次数(重复发生)?

我目前有这个脚本

//COUNT VAL
var curr = '';
var previous = '';
var arr = new Array();
var sorted = count.sort();
for(var c=0; c < sorted.length; c++){
if(sorted[c] != ''){
if(sorted[c] != curr){
var repeat = 1;
arr[sorted[c]] = repeat;
curr = sorted[c];
}
else if(sorted[c] == curr){
repeat++;
}
}
}
alert(JSON.stringify(arr));

数组“count”的值是(我使用JSON.stringify):

[" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null]

我希望我的脚本显示...(我希望它能返回一个数组)

[1: 10, 2: 3]

(x:y)x是数字,y是重复的次数。

我得到了什么......

[null,1,1]

5 个答案:

答案 0 :(得分:2)

var a = [" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null];

var counts = a.reduce( function(obj, cur){
    if( !obj[cur] ) {
        obj[cur] = 0;
    }
    obj[cur]++;
    return obj;
}, {});

结果

2: 3
1: 10
null: 13

答案 1 :(得分:1)

使用您的代码,

像这样修改你的循环,

for(var c=0; c < sorted.length; c++){
 if(sorted[c] != ''){
    if(arr[sorted[c]] ){
        var count = arr[sorted[c]];
        count++;
        arr[sorted[c]] = count;
    }
    else{
        arr[sorted[c]] = 1;
    }
 }
}

答案 2 :(得分:1)

这将为您提供摘要,忽略空值

var collection = [" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null];

var summary = collection.reduce(function(a, b) {
    var tmp = parseInt(b)
    if (!isNaN(tmp)) {
        if (!a[tmp]) {
            a[tmp] = 0;
        }
        a[tmp]++;
    }
    return a;
}, {});

console.log(summary);

答案 3 :(得分:0)

不确定它是否是最佳解决方案,但它可以正常工作并将输出保存在数组中。

var arr = [" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null];

var obj = {};
var final = [];
var count = 0;
for(var i=0,len=arr.length;i<len;i++){
  if(arr[i] in obj){
     final[obj[arr[i]]] ++;
  }
  else{ 
     obj[arr[i]] = count;
     final[count] = 1;
     count++;
  } 
}

console.log(final);

答案 4 :(得分:0)

试试这个:

var repeated = function repeated(arr){
                var res = {};
                for(index in arr){
                    var x = arr[index];
                    if(!res.hasOwnProperty(x))
                        res[x] = 0;    
                    res[x]++;
                }
                return res;
            }