0

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

1
  • What have you tried? Did you attempt to solve this yourself? Provide some code sample. Stackoverflow is here to help but not to solve the whole problem for you. Commented Jul 27, 2020 at 5:14

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.