Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Reducing object with underscore

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!

like image 527
vincewilfork Avatar asked Oct 23 '13 16:10

vincewilfork


1 Answers

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

like image 140
redmallard Avatar answered Sep 28 '22 08:09

redmallard