2

I have an array of objects that looks like this:

const users = [{name: 'John', gender: 'Male', orders: 20},
    {name: 'Doe', gender: 'Male', orders: 8},
    {name: 'Ada', gender: 'Female', orders: 10},
    {name: 'David', gender: 'Male', orders: 30}];

I need to count the number of duplicate genders and sum up the amount of orders based on gender located in the objects. I would like the final array to look like this:

[{gender: 'Male', count: 3, totalOrders: 58}, {gender: 'Female', count: 1, totalOrders: 10}]

This is the code I have so far:

const usersGender = users.map((user) => user.gender);

const result = Object.values(usersGender.reduce((a, b) => {
  a[b] = a[b] || [b, 0];
  a[b][1]++;
  return a;
},{})).map(item => ({gender: item[0], count : item[1]}));

console.log(result);

My output from the code above is:

[{ gender: 'Male', count: 3 }, { gender: 'Female', count: 1 }]

Thank you.

1 Answer 1

6

You could collect with an object and get the values from it.

const
    users = [{ name: 'John', gender: 'Male', orders: 20 }, { name: 'Doe', gender: 'Male', orders: 8 }, { name: 'Ada', gender: 'Female', orders: 10 }, { name: 'David', gender: 'Male', orders: 30 }],
    result = Object.values(users.reduce((r, { gender, orders }) => {
        r[gender] ??= { gender, count: 0, totalOrders: 0 };
        r[gender].count++;
        r[gender].totalOrders += orders;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.