Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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
// }
like image 339
josh_c Avatar asked Sep 06 '25 03:09

josh_c


1 Answers

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);
like image 121
Nina Scholz Avatar answered Sep 08 '25 05:09

Nina Scholz