Good day!
I need some help regarding grouping array values to get the summation.
I have an array like this:
ArrInput = [
{
“year”:2019,
“id”:“book”,
“price”:500.00
},
{
“year”:2019,
“id”:“magazine”,
“price”:300.00
},
{
“year”:2019,
“id”:“book”,
“price”:300.00
}
];
Is it possible to group the values to get the summation? Example is like this one:
ArrResult = [
{
“year”:2019,
“id”:“book”,
“price”:800.00
},
{
“year”:2019,
“id”:“magazine”,
“price”:300.00
}
]
Here’s a way, using reduce.
function combineItem(resultItem, item) {
return {
"year": Math.max(resultItem.year, item.year),
"id": item.id,
"price": resultItem.price + item.price
};
}
function itemsReducer(resultItems, item) {
const updateIndex = resultItems.findIndex(function(resultItem) {
return resultItem.id === item.id;
});
if (updateIndex === -1) {
return resultItems.concat(item);
}
resultItems[updateIndex] = combineItem(resultItems[updateIndex], item);
return resultItems;
}
ArrResult = ArrInput.reduce(itemsReducer, []);
With the year I’ve decided to select the most recent year when adding them together.
2 Likes
Thank you very much for your help!
system
Closed
5
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.