-1

I have an array I need to merge duplicate values with the sum of amount. What would be an efficient algorithm

var arr = [{
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 1
}, {
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 2
}, {
    item: {
        id: 2,
        name: "Abc"
    },
    amount: 2
},{
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 2
}]

I need solution as

[{
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 5
}, {
    item: {
        id: 2,
        name: "Abc"
    },
] amount: 2
}]
2

2 Answers 2

4

simply use Object.values() with Array.reudce() to merge objects and then get the values:

var arr = [{ item: { id: 1, name: "Abc" }, amount: 1 }, { item: { id: 1, name: "Abc" }, amount: 2 }, { item: { id: 2, name: "Abc" }, amount: 2 },{ item: { id: 1, name: "Abc" }, amount: 2 }];

var result = Object.values(arr.reduce((a,curr)=>{

  if(!a[curr.item.id])
    a[curr.item.id] = Object.assign({},curr); // Object.assign() is used so that the original element(object) is not mutated.
   else 
     a[curr.item.id].amount += curr.amount;
    return a;
},{}));

console.log(result);

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

Comments

1

used map to catch em all :D

var arr = [{ item: { id: 1, name: "Abc" }, amount: 1 }, { item: { id: 1, name: "Abc" }, amount: 2 }, { item: { id: 2, name: "Abc" }, amount: 2 },{ item: { id: 1, name: "Abc" }, amount: 2 }];

var res = {};
arr.map((e) => {
  if(!res[e.item.id]) res[e.item.id] = Object.assign({},e); // clone, credits to: @amrender singh
  else res[e.item.id].amount += e.amount;
});
console.log(Object.values(res));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.