Reputation: 11
I want to reduce the object to one when the label is the same, and sum its value, however, needs to avoid the object with both same values of label and value, here is the example:
let arr = [
{
label: "▲",
value: 5
},
{
label: "▲",
value: 10
},
{
label: "■",
value: 13
},
{
label: "●",
value: 4
},
{
label: "■",
value: 6
},
{
label: "■",
value: 6
},
]
let expectedResult = [
{
label: "▲",
value: 15
},
{
label: "■",
value: 19
},
{
label: "●",
value: 4
},
]
I tried to use let newArr = [...new Set(arr)]
, but it returned the same array.
Upvotes: 1
Views: 49
Reputation: 6049
You can make use of Array.reduce
and Object.values
and achieve the expected output.
let arr = [{label:"▲",value:5},{label:"▲",value:10},{label:"■",value:13},{label:"●",value:4},{label:"■",value:6},{label:"■",value:6},]
const getReducedData = (data) => Object.values(data.reduce((acc, obj) => {
if(acc[obj.label]) {
acc[obj.label].value += obj.value;
} else {
acc[obj.label] = { ...obj }
}
return acc;
}, {}));
console.log(getReducedData(arr));
.as-console-wrapper {
max-height: 100% !important;
}
Upvotes: 1