简体   繁体   中英

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.

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM