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);