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
// }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With