Map Reducing object with underscore

vincewilfork picture vincewilfork · Oct 23, 2013 · Viewed 11.1k times · Source

I want to reduce this object to just an object containing product name and average price. What's the fastest way to do it?

var foo = { group1: [
        {
            name: "one",
            price: 100
        },
        {
            name: "two",
            price: 100
        }],
       group2: [
        {
            name: "one",
            price: 200
        },
        {
            name: "two",
            price: 200
        }],
       group3: [
        {
            name: "one",
            price: 300
        },
        {
            name: "two",
            price: 300
        }]
      }

resulting in

var foo2 = [{  
               name: 'one',  
               price: 200
            },{
               name: 'two', 
               price: 200
            }];

Thanks!

Answer

redmallard picture redmallard · Oct 26, 2013

Not to rain on Evan's parade, but here's an alternative that is a bit shorter ;)

result = _.chain(original)
  .flatten()
  .groupBy(function(value) { return value.name; })
  .map(function(value, key) {
    var sum = _.reduce(value, function(memo, val) { return memo + val.price; }, 0);
    return {name: key, price: sum / value.length};
  })
  .value();

See it in action: http://plnkr.co/edit/lcmZoLkrlfoV8CGN4Pun?p=preview