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:

The Weekender: Moon metaphors, procrastinating monks, and a visit to a cheese factory

What we’re reading, watching, and listening to this week ͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ...

Contact Form

Name

Email *

Message *