Having a matrix which contains many sub-arrays. Each array has the same length and each first element of them is a string followed by numeric elements having this form:
myArray = [
["revenues", 10, 20, 30],
["expenses", 1, 1, 1],
["expenses", 2, 3, 4],
["revenues", 5, 6, 7],
];
My goal is to combine them by string and compute the sum on each position. For the above example the result must be:
result = [
["revenues", 15, 26, 37],
["expenses", 3, 4, 5],
];
I tried to do it by mapping them by the value of the string and than compute sum for each position. It's only for the sub-arrays strings containing "revenues" in the first phase but still not working.
result = myArray.map(s => s[0].includes("revenues")).reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
Any suggestions?
You could find the sub array in the temporary result or add that array to the result set.
var array = [["revenues", 10, 20, 30], ["expenses", 1, 1, 1], ["expenses", 2, 3, 4], ["revenues", 5, 6, 7]],
result = array.reduce((r, a) => {
var sub = r.find(([key]) => key === a[0]);
if (!sub) {
return r.concat([a]);
}
a.forEach((v, i) => i && (sub[i] += v));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }