Skip to content

Instantly share code, notes, and snippets.

@ramsunvtech
Created January 7, 2021 05:23
Show Gist options
  • Save ramsunvtech/41b2a7071a224be975fe7fdec7f54055 to your computer and use it in GitHub Desktop.
Save ramsunvtech/41b2a7071a224be975fe7fdec7f54055 to your computer and use it in GitHub Desktop.
Group and Sum Array Items
// 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