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?
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.
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.
The length property sets or returns the number of elements in an array.
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);
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) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With