Javascript 计算对象数组中特定属性值的出现次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45547504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting occurrences of particular property value in array of objects
提问by moonshine
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.
如果我给 id 12,我想要 3。
How can i do that?
我怎样才能做到这一点?
回答by Alberto Trindade Tavares
A simple ES6 solution is using filterto get the elements with matching id and, then, get the length of the filtered array:
一个简单的 ES6 解决方案filter用于获取具有匹配 id 的元素,然后获取过滤后数组的长度:
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 reduceas suggested by @YosvelQuintero:
编辑:另一种解决方案,即更有效(因为它不产生一个新的数组),是使用reduce作为由@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);
回答by adeneo
You count
你算
var arr = [
{id: 12, name: 'toto'},
{id: 12, name: 'toto'},
{id: 42, name: 'tutu'},
{id: 12, name: 'toto'}
]
function getNbOccur(id, arr) {
var occurs = 0;
for (var i=0; i<arr.length; i++) {
if ( 'id' in arr[i] && arr[i].id === id ) occurs++;
}
return occurs;
}
console.log( getNbOccur(12, arr) )

