-4

What is the best way to take the following array of objects and combine them by key and accumulate the price so that the this:

var sales = [
{
    order_id: 138,
    price: 25,
},
{
    order_id: 138,
    price: 30,
},
{
    order_id: 139,
    price: 15,
},
{
    order_id: 131,
    price: 25,
}, 

];

become this:

var sales = [
    {
        order_id: 138,
        price: 55,
    },
    {
        order_id: 139,
        price: 15,
    },
    {
        order_id: 131,
        price: 25,
    }, 
];

Note that the initial array will contain 500+ items. Is this a good usecase for reduce? or do I need to build a whole new array with a for loop?

Andreas
  • 21,535
  • 7
  • 47
  • 56
Malibur
  • 1,695
  • 5
  • 22
  • 31
  • 1
    Neither your desired format not starting format is not valid — you have an object with multiple keys. Is that supposed to be an array? – Mark Apr 30 '18 at 15:13
  • I think you want to map/reduce (it should be a good keyword for a google search) ;) but as everyone stated, there is no array here! – sjahan Apr 30 '18 at 15:13
  • 1
    This doesn't make any sense. `item` key is repeated. Objects cannot have duplicate keys. – 31piy Apr 30 '18 at 15:13
  • Apologies, I was confusing my syntax. I think I've edited it to be correct now. Does the question make more sense now? – Malibur Apr 30 '18 at 15:23
  • 1
    Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Andreas Apr 30 '18 at 15:37

1 Answers1

1
var sales = [
{
    order_id: 138,
    price: 25,
},
{
    order_id: 138,
    price: 30,
},
{
    order_id: 139,
    price: 15,
},
{
    order_id: 131,
    price: 25,
}, 
];

var buf = {}

sales.map(obj => {
    if(buf[obj.order_id]) {
        buf[obj.order_id].price += obj.price
    } else {
        buf[obj.order_id] = obj
    }
})

var result = Object.values(buf)
console.log(result)
wang
  • 1,660
  • 9
  • 20
  • Thank you! - I ended up doing a similar thing with .reduce() and .findIndex() — not sure which performs better. – Malibur Apr 30 '18 at 17:10