[英]JS Removing duplicates from Multidimensional array
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.我尝试使用
let newArr = [...new Set(arr)]
,但它返回了相同的数组。
You can make use of Array.reduce
and Object.values
and achieve the expected output.您可以使用
Array.reduce
和Object.values
并实现预期的输出。
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.