Counting occurrences of particular property value in array of objects
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) )
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);