如何计算 Javascript 对象数组中不同值出现的次数? [英] How to count number of occurrences of distinct values from an array of objects in Javascript?
本文介绍了如何计算 Javascript 对象数组中不同值出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面这样的对象数组:
I have an array of objects like below:
var array =
[
{"name":"abc","age":20}
{"name":"abc","age":20}
{"name":"abc","age":20}
{"name":"xyz","age":21}
{"name":"xyz","age":21}
]
我想计算不同值的出现次数,例如:
I want to count the number of occurrences of distinct values like:
[3,2]
假设 abc
出现 3 次,xyz
出现 2 次.
Assuming abc
has 3 occurrences and xyz
has 2 occurrences.
我在 reactjs
中做这件事.我能够使用 这个答案.
I am doing it in reactjs
. I am able to get distinct values like [abc,xyz]
using this answer.
首选 ES6 语法.
推荐答案
你需要知道一个计数属于哪个名字,所以我建议不要输出一个不给你任何线索的数组,而是一个键控的对象按名称和相应的计数作为值:
You'll need to know to which name a count belongs, so I propose not to output an array that gives you no clue about that, but an object keyed by names and with as value the corresponding count:
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);
这篇关于如何计算 Javascript 对象数组中不同值出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文