开发者问题收集

如何计算 Javascript 中对象数组中不同值出现的次数?

2017-04-28
17543

我有如下对象数组:

var array =
    [
        {"name":"abc","age":20}
        {"name":"abc","age":20}
        {"name":"abc","age":20}
        {"name":"xyz","age":21}
        {"name":"xyz","age":21}
    ]

我想计算不同值的出现次数,例如:

[3,2]

假设 abc 出现 3 次, xyz 出现 2 次。

我在 reactjs 中执行此操作。我可以使用 此答案 获取不同值,例如 [abc,xyz]

首选 ES6 语法。

3个回答

您需要知道计数属于哪个名称,因此我建议不要输出一个无法提供任何线索的数组,而是一个以名称为键并以相应计数为值的对象:

var result = array.reduce( (acc, o) => (acc[o.name] = (acc[o.name] || 0)+1, acc), {} );
var array =
    [
        {"name":"abc","age":20},
        {"name":"abc","age":20},
        {"name":"abc","age":20},
        {"name":"xyz","age":21},
        {"name":"xyz","age":21}
    ];
    
var result = array.reduce( (acc, o) => (acc[o.name] = (acc[o.name] || 0)+1, acc), {} );

console.log(result);
trincot
2017-04-28

Map/Reduce 来救援:

const frequency = array
  .map(({ name }) => name)
  .reduce((names, name) => {
    const count = names[name] || 0;
    names[name] = count + 1;
    return names;
  }, {});

// frequency: { abc: 3, xyz: 2 }
LetterEh
2017-04-28

您可以使用 forEach/map 来迭代数组并将计数存储在另一个变量中,检查这个:

var array = [
     {"name" : "abc", "age" : 20},
     {"name" : "abc", "age" : 20},
     {"name" : "abc", "age" : 20},
     {"name" : "xyz", "age" : 21},
     {"name" : "xyz", "age" : 21},
];
    
let b = {};

array.forEach(el => {
    b[el.name] = (b[el.name] || 0) + 1;
})

console.log(b);
Mayank Shukla
2017-04-28