I have an array of JavaScript Objects. Each object contains an array data
, which is the main focus here. My goal is to aggregate all arrays with the same name across different objects (the ids are not important for this process as I intend to visualize the data in a chart later).
norm.series = [
{ id: "qah01", name: "Bingo", data: [ ["date1", 1.5] ] },
{ id: "qah02", name: "Combo", data: [ ["date2", 2.5] ] },
{id: "qah03", name: "Bingo", data: [ ["date1", 0.5], ["date3", 1.2], ["date4", 2.0] ] },
{ id: "qah04", name: "Sango", data: [ ["date7", 3.2], ["date8", 2.8] ] }
]
What I am trying to achieve:
norm.series [
{ id: "qah01", name: "Bingo", data: [ [date1, 2.0], [date3, 1.2], [date4, 2.0] ] },
{ id: "qah02", name: "Combo", data: [ [date2, 2.5] ] },
{ id: "qah04", name: "Sango", data: [ [date7, 3.2], [date8, 2.8] ] }
]
This is my current progress:
const result = norm.series.reduce((acc, d) => {
const found = acc.find((a, index) => a.data[index][0] === d.data[index][0]);
const newData = a.data[index][1] + d.data[index][1];
if (!found) {
acc.push({id: d.id, name:d.name, data: d.data})
}
else {
found.data.push(newData);
}
return acc;
}, []);