Count values of an array and add them to an object (TypeScript)

I have this object, and I would like to know how many items there are for each user and add them to a new object (users are dynamic)

[{
    "user": "user1"
  }, {
    "user": "user1"
  }, {
    "user": "user2"
  }, {
    "user": "user3"
}]

For example, with the previous object you should create a new one like this:

[{"user":"user1", "count": 2},{"user":"user2","count":1},{"user":"user3","count":1}]

I had tried a filter, doing something like this

const count = (array, user) => {
        return array.filter(n => n.user=== user).length;
      };

But the new object was created by harcode

I would very much appreciate your help

Upvotes: 0

Views: 239

Answers (1)

yurzui
yurzui

Reputation: 214017

I would do it with the help of Array.prototype.reduce method:

const arr = [
  {
    "user": "user1"
  }, {
    "user": "user1"
  }, {
    "user": "user2"
  }, {
    "user": "user3"
  }
];

const usersByCountMap = arr.reduce((acc, cur) => {
  acc[cur.user] = (acc[cur.user] || 0) + 1;

  return acc;
}, {});

const usersByCountArr = Object.keys(usersByCountMap).map(key => ({ user: key, count: usersByCountMap[key ]}));

console.log(usersByCountArr);

Upvotes: 3

Related Questions