计算对象数组中特定属性值的出现次数 [英] Counting occurrences of particular property value in array of objects
本文介绍了计算对象数组中特定属性值的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何计算这样一个对象数组的出现次数:
<预><代码>[{编号:12,名称 : toto,},{编号:12,名称 : toto,},{编号:42,名称:芭蕾舞短裙,},{编号:12,名称 : toto,},]在这种情况下,我想要一个函数来给我这个:
getNbOccur(id){//不知道...//发生返回;}
如果我给 id 12,我想要 3.
我该怎么做?
解决方案
一个简单的 ES6 解决方案是使用 filter
获取匹配 id 的元素,然后获取过滤后数组的长度:
const array = [{id: 12, name: 'toto'},{id: 12, name: 'toto'},{id: 42, name: 'tutu'},{id: 12, name: 'toto'},];常量 ID = 12;const count = array.filter((obj) => obj.id === id).length;console.log(count);
编辑:另一种更有效的解决方案(因为它不生成新数组)是使用 reduce
作为 @YosvelQuintero 建议:
const array = [{id: 12, name: 'toto'},{id: 12, name: 'toto'},{id: 42, name: 'tutu'},{id: 12, name: 'toto'},];常量 ID = 12;const count = array.reduce((acc, cur) => cur.id === id ? ++acc : acc, 0);console.log(count);
I would like to know how i can count the number of occurences on an array of object like this one :
[
{id : 12,
name : toto,
},
{id : 12,
name : toto,
},
{id : 42,
name : tutu,
},
{id : 12,
name : toto,
},
]
in this case i would like to have a function who give me this :
getNbOccur(id){
//don't know...//
return occurs;
}
and if i give the id 12 i would like to have 3.
How can i do that?
解决方案
A simple ES6 solution is using filter
to get the elements with matching id and, then, get the length of the filtered array:
const array = [
{id: 12, name: 'toto'},
{id: 12, name: 'toto'},
{id: 42, name: 'tutu'},
{id: 12, name: 'toto'},
];
const id = 12;
const count = array.filter((obj) => obj.id === id).length;
console.log(count);
Edit: Another solution, that is more efficient (since it does not generate a new array), is the usage of reduce
as suggested by @YosvelQuintero:
const array = [
{id: 12, name: 'toto'},
{id: 12, name: 'toto'},
{id: 42, name: 'tutu'},
{id: 12, name: 'toto'},
];
const id = 12;
const count = array.reduce((acc, cur) => cur.id === id ? ++acc : acc, 0);
console.log(count);
这篇关于计算对象数组中特定属性值的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文