I have array of object whose element contains an array property. I need to reduce the array to shorter one based the label value and merge and replace _data array to new one like this below:
const originalArray = [
{ label: "approved", data: [1, 0, 0, 0, 0, 0, 0] },
{ label: "approved", data: [0, 2, 0, 0, 0, 0, 0] },
{ label: "rejected", data: [0, 0, 3, 0, 0, 0, 0] },
{ label: "rejected", data: [0, 0, 0, 1, 0, 0, 0] },
{ label: "pending", data: [0, 1, 0, 0, 0, 0, 0] },
{ label: "pending", data: [0, 0, 0, 0, 0, 7, 0] }
];
const expectedArray = [
{ label: "approved", data: [1, 2, 0, 0, 0, 0, 0] },
{ label: "rejected", data: [0, 0, 3, 1, 0, 0, 0] },
{ label: "pending", data: [0, 1, 0, 0, 0, 7, 0] },
]
I tried to merge the data property of each element by label and then create a unique array from it
3
Answers
You could do this using
reduce
but it’s perhaps slightly more straightforward to just accumulate the values for each label into an object, then unpack it into your desired array form:You can first aggregate the arrays by label into a map, then merge them.
Use
Array.prototype.reduce()
to accumulate an object where each key is unique to label, for each loop if the label already exists in the accumulator object, then add data array with the accumulator’s data (corresponding values). If the object with the label does not exist then a new object is created with the corresponding label as key.We then just take values array from the accumulated object using
Object.values()
.