0

I need to combine the objects whose prices are the same and add the quantity (amount).

Example:

[
    {price: 25.1, amount: 32},
    {price: 45.2, amount: 45},
    {price: 25.1, amount: 25},
    {price: 44.0, amount: 13},
    {price: 45.2, amount: 23}
]

Result:

[
    {price: 25.1, amount: 57}, // 32 + 25
    {price: 45.2, amount: 68}, // 45 + 23
    {price: 44.0, amount: 13},
]
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Arthur
  • 3,056
  • 7
  • 31
  • 61

1 Answers1

2

You can use Array#reduce with an object to store the amount for each price.

const example = [
    {price: 25.1, amount: 32},
    {price: 45.2, amount: 45},
    {price: 25.1, amount: 25},
    {price: 44.0, amount: 13},
    {price: 45.2, amount: 23}
]
const res = Object.values(example.reduce((acc,{price,amount})=>
   ((acc[price] = acc[price] || {price, amount: 0}).amount += amount, acc), {}));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80