JavaScript Using Reduce To Create Object With Counts, From Array
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
Solution 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);
Solution 2:
const groupedByName = people.reduce((obj, person) => {
const count = obj[person] || 0
return { ...obj, [person]: count + 1 }
}, {})
Working codepen
Post a Comment for "JavaScript Using Reduce To Create Object With Counts, From Array"