Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
}]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
303 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...