1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.