数组比较并获取计数

时间:2015-03-23 13:31:33

标签: javascript jquery arrays object

我是新手。我有多个数组列表:

    var fruits1 = ["A", "B", "C", "D"];
    var fruits2 = ["O", "E", "F", "G"];
    var fruits3 = ["S", "D", "E", "S"];
    var fruits4 = ["A", "B", "Z", "A"];
    var fruits5 = ["A", "R", "U", "V"];
    var fruits6 = ["N", "B", "O", "M"];
    var fruits7 = ["A", "B", "N", "P"];
    var fruits8 = ["X", "C", "Z", "Z"];
    var fruits9 = ["X", "B", "X", "B"];

该数组具有如下事项的次数。

    A - 5
    B - 6
    C - 2
    D - 2
    E - 2
    F - 1
    G - 1
    M - 1
    N - 2
    O - 2
    P - 1
    R - 1
    S - 2
    U - 1
    V - 1
    X - 3
    Z - 3

需要使用javascript / jquery

输出
[{"B" : 6}, { "A" : 5}, {"X":3}, {"Z" : 3}, {"C" : 2}, { "D" : 2}, { "E" : 2}, { "N" : 2}, { "O" :2}, { "S" : 2}, { "F": 1 }, { "G" :1}, { "M" :1}, { "P" :1}, { "R" :1}, { "U" :1}, { "V" :1 }]

有人可以这么做吗?

2 个答案:

答案 0 :(得分:3)

我可能会过度思考这个问题,但这就是我的想法:

var fruits1 = ["A", "B", "C", "D"],
    fruits2 = ["O", "E", "F", "G"],
    fruits3 = ["S", "D", "E", "S"],
    fruits4 = ["A", "B", "Z", "A"],
    fruits5 = ["A", "R", "U", "V"],
    fruits6 = ["N", "B", "O", "M"],
    fruits7 = ["A", "B", "N", "P"],
    fruits8 = ["X", "C", "Z", "Z"],
    fruits9 = ["X", "B", "X", "B"],
    fruits= [].concat(fruits1, fruits2, fruits3, fruits4, fruits5, fruits6, fruits7, fruits8, fruits9),
    cnt= {},
    output= [];

fruits.forEach(function(val) {
  cnt[val]= (cnt[val] || 0)+1
});

Object.keys(cnt).forEach(function(val, idx) {
  var obj= {};
  obj[val]= cnt[val];
  output.push(obj);
});

output= output.sort(function(a, b) {
  var ak= Object.keys(a)[0],
      bk= Object.keys(b)[0],
      a1= a[ak],
      b1= b[bk];
  return a1 < b1 ? 1 : a1 > b1 ? -1 : 
         ak < bk ? -1 : ak > bk ? 1 : 0;
});

document.querySelector('#output').innerHTML= JSON.stringify(output);
<div id="output"></div>

concat函数将所有数组连接成一个名为fruit的数组。

fruits.forEach循环将总成果存储在cnt对象中,如下所示:{"A": 5, "B": 6, "C": 2, ...}

Object.keys(cnt).forEach循环将cnt键推送到output数组。

然后output.sort函数对值进行排序,首先按项目数减少,然后按升序键排序。

答案 1 :(得分:1)

我建议您只拥有所有水果的数组,然后使用以下映射 -

即。在你的情况下,我将数组合并为单一 -

var fruits = ["A", "B", "C", "D","O", "E", "F", "G","S", "D", "E", "S","A", "B", "Z", "A","A", "R", "U", "V","N", "B", "O", "M","A", "B", "N", "P","X", "C", "Z", "Z","X", "B", "X", "B"];

然后 -

var counts = {};

for(var i = 0; i< fruits.length; i++) {
    var fruit = fruits[i];
    counts[fruit] = counts[fruit] ? counts[fruit]+1 : 1;

}

Demo