What is the best way to reduce and merge a collection of objects

Tags: , , ,



So I reached a dilemma this week while trying to solve what seemed to be an easy problem, but I was wrong.

Sample code:

let arr = [
  { id: 'ae0123', cost: 100.00, orders: 5 },
  { id: 'ae0123', cost: 50.00, orders: 5 },
  { id: 'ae4321', cost: 75.00, orders: 1 }
]

So the problem was being able to map through the array and merge/sum the values if their unique identifiers match.

Any suggestions?

End result would look something like this:

[
  { id: 'ae0123', cost: 150.00, orders: 10 },
  { id: 'ae4321', cost: 75.00, orders: 1 }
]

Now of course the real application will not have statically typed ids, but they were written into this example. So please take that into consideration.

Thanks in advance!

Answer

You could take an object for grouping and an array for adding the wanted properties.

let array = [{ id: 'ae0123', cost: 100.00, orders: 5 }, { id: 'ae0123', cost: 50.00, orders: 5 }, { id: 'ae4321', cost: 75.00, orders: 1 }],
    result = Object.values(array.reduce((r, o) => {
        if (r[o.id]) {
            ['cost', 'orders'].forEach(k => r[o.id][k] += o[k]);
        } else {       
            r[o.id] = { ...o };
        }
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Source: stackoverflow