How to get the count of same data in array of object with the info about number of count

Viewed 75

suppose I have an array of object arr1

arr1 = [{name: "name1",id: 1},{name: "name2",id: 1},{name: "name3",id: 4},{name: "name3",id: 3},{name: "name1",id: 5}]

I want the information of count having same id in array or object form.

I tried to get the info using for loop , map and Lodash. I got the result. But want o do it in any efficient way.

My working code

const arr1 = [{name: "name1",id: 1},{name: "name2",id: 1},{name: "name3",id: 4},{name: "name3",id: 3},{name: "name1",id: 5}];

const arr2 = []
for (var i = 0; i < arr1.length; i++) {
  var obj = {}
  _.keys(arr1[i]).map(o => {
    obj[o] = arr1[i][o]
    obj["count"] = arr1.filter(a => {
      return a.id === arr1[i].id
    }).length
  })
  arr2.push(obj)
}
var arr3 = _.uniqBy(arr2, "id")

console.log(arr3);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

2 Answers

Group by the id, and map the groups. Convert each group to an object that is based on the first object in the group + the length of the group as the count:

const arr = [{name: "name1",id: 1},{name: "name2",id: 1},{name: "name3",id: 4},{name: "name3",id: 3},{name: "name1",id: 5}];

const result = _(arr)
  .groupBy('id')
  .map(group => ({ ...group[0], count: group.length }))
  .value();
  
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

  1. Get the count of all items based on their id by using countBy.
  2. Remove duplicates with uniqBy.
  3. Add the count with map.

The last two can be done in a chained operation which will do lazy evaluation instead of two full loops.

const arr1 = [{name: "name1",id: 1},{name: "name2",id: 1},{name: "name3",id: 4},{name: "name3",id: 3},{name: "name1",id: 5}];

const counts = _.countBy(arr1, "id");

const result = _(arr1)
  .uniqBy("id")
  .map(x => ({...x, count: counts[x.id]}))
  .value();
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

Related