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},
]
0

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.