Counting occurrences of particular property value in array of objects [duplicate]

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?


Solution 1:

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

Solution 2:

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