Created
January 7, 2021 05:23
-
-
Save ramsunvtech/41b2a7071a224be975fe7fdec7f54055 to your computer and use it in GitHub Desktop.
Group and Sum Array Items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Group and sum the value. | |
function groupAndSum(list) { | |
const existingItems = {} | |
list.forEach((item) => { | |
if (!existingItems[item.name]) { | |
existingItems[item.name] = item; | |
return; | |
} | |
existingItems[item.name] = { | |
...existingItems[item.name], | |
amount: item.amount + existingItems[item.name].amount, | |
} | |
}); | |
return Object.values(existingItems); | |
} | |
// Usage | |
var duplicatedItems = [ | |
{ | |
name: "a", | |
amount: 1, | |
}, | |
{ | |
name: "a", | |
amount: 4, | |
}, | |
{ | |
name: "b", | |
amount: 2, | |
}, | |
]; | |
groupAndSum( | |
duplicatedItems | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment