4

I'm trying to solve this little problem, where I need to use reduce to create an object with the counts of each item.

I thought I understood how reduce works, using a function to get multiple values down to one, yet I cannot figure out how this is to work.

Any ideas or advice? I really appreciate it.

// var people = ['josh', 'dan', 'sarah', 'joey', 'dan', 'josh', 'francis', 'dean'];

// can reduce be used to get: 

// { 
//   josh: 2,
//   dan: 2, 
//   sarah: 1,
//   joey: 1,
//   francis: 1,
//   dean: 1
// }

2 Answers 2

4

As you see, you need an object as result set for the count of the items of the array.

For getting the result, you could take a default value of zero for adding one to count the actual value, while you use the given name as property for counting.

var people = ['josh', 'dan', 'sarah', 'joey', 'dan', 'josh', 'francis', 'dean'],
    counts = people.reduce(function (c, p) {
        c[p] = (c[p] || 0) + 1;
        return c;
    }, Object.create(null));
    
console.log(counts);

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

Comments

0
const groupedByName = people.reduce((obj, person) => {
  const count = obj[person] || 0
  return { ...obj, [person]: count + 1 }
}, {})

Working codepen

1 Comment

This was from a functional programming course I am taking. I thought it was nice.

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.