Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 908
moonshine Avatar asked Aug 07 '17 12:08

moonshine


People also ask

How do you count duplicate values in an array?

To count the duplicates in an array:Copied! const arr = ['one', 'two', 'one', 'one', 'two', 'three']; const count = {}; arr. forEach(element => { count[element] = (count[element] || 0) + 1; }); // 👇️ {one: 3, two: 2, three: 1} console.

How do you find duplicate objects in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

Which property is used to count elements of an array?

The length property sets or returns the number of elements in an array.


2 Answers

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);
like image 59
Alberto Trindade Tavares Avatar answered Oct 17 '22 10:10

Alberto Trindade Tavares


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) )
like image 28
adeneo Avatar answered Oct 17 '22 12:10

adeneo