I have the following object:
var series = [{
name: 'Series 1',
data: [1400, 999, 450],
tag: "Tag 1"
}, {
name: 'Series 2',
data: [355, 188, 99],
tag: "Tag 1"
}, {
name: 'Series 3',
data: [205, 488, 104],
tag: "Tag 2"
}];
What I'm trying to do is to perform a groupBy function to that array so for example, calling orderBy("tag") should return the following output:
[{
name: "Series 1 / Series 2",
data: [1755, 1187, 549], // => Sum: Series1[0] + Series2[0], Series1[1] + Series2[1], etc...
tag: "Tag 1"
}, {
name "Series 3",
data: [205, 488, 104],
tag: "Tag 2"
}]
At the moment this is what I've so far:
var seriesArray = [{
name: 'Series 1',
data: [1400, 999, 450],
tag: "Tag 1"
}, {
name: 'Series 2',
data: [355, 188, 99],
tag: "Tag 1"
}, {
name: 'Series 3',
data: [205, 488, 104],
tag: "Tag 2"
}];
const groupBy = (key) => seriesArray.reduce((total, currentValue) => {
const newTotal = total;
if (
total.length &&
total[total.length - 1][key] === currentValue[key]
)
newTotal[total.length - 1] = {
...total[total.length - 1],
...currentValue,
data: parseInt(total[total.length - 1].data[0]) + parseInt(currentValue.data[0]),
};
else newTotal[total.length] = currentValue;
return newTotal;
}, []);
console.log(groupBy('tag'));
As you can see it seems to work the orderBy("tag") but I'm doing the sum operation explicit, the main problem with this is that data[] could have X elements.