0

配列メンバーとそれらが繰り返される回数(繰り返し)を取得するにはどうすればよいですか?

私は現在このスクリプトを持っています

//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]
4

5 に答える 5

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
于 2012-07-09T07:26:50.213 に答える
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;
    }
 }
}
于 2012-07-09T07:33:22.320 に答える
1

これにより、null値を無視して、要約が表示されます

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);
于 2012-07-09T07:38:36.120 に答える
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);
于 2012-07-09T07:47:18.910 に答える
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;
            }
于 2012-07-09T08:18:47.533 に答える