[英]JS Removing duplicates from Multidimensional array
我想在標簽相同時將對象減少到一,並將其值相加,但是,需要避免標簽和值的值都相同的對象,這是示例:
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
},
]
我嘗試使用let newArr = [...new Set(arr)]
,但它返回了相同的數組。
您可以使用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.