Reduce array of objects on key and sum value into array

You can get all the unique names using map() and uniq(), and then map() each name to get their respective sums using sumBy().
var data = [
  { name: 'foo', type: 'fizz', val: 9 },
  { name: 'foo', type: 'buzz', val: 3 },
  { name: 'bar', type: 'fizz', val: 4 },
  { name: 'bar', type: 'buzz', val: 7 }
];

var result = _(data)
  .map('name')
  .uniq()
  .map(key => ({ 
    key, 
    val: _(data).filter({ name: key }).sumBy('val')
  }))
  .value();

console.log(result);

No comments:

What is Security Engineering? Part 2.

A broad overview of the ever-developing security engineering field; a domain that can feel intimidating to some software engineers. With Nie...

Contact Form

Name

Email *

Message *