根据子数组的位置和数组的第一个元素计算子数组元素的总和

Compute sum of elements of sub-arrays based on their position and first element of array

有一个包含许多子数组的矩阵。每个数组都具有相同的长度,并且它们的每个第一个元素都是一个字符串,后跟具有以下形式的数字元素:

myArray = [
        ["revenues", 10, 20, 30],
        ["expenses", 1, 1, 1],
        ["expenses", 2, 3, 4],
        ["revenues", 5, 6, 7],
];

我的目标是按字符串组合它们并计算每个位置的总和。对于上面的例子,结果必须是:

result = [
        ["revenues", 15, 26, 37],
        ["expenses", 3, 4, 5],
];

我试图通过将它们映射到字符串的值而不是计算每个位置的总和来做到这一点。仅针对第一阶段包含"revenues"的子数组字符串,但仍然不起作用。

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;
    }, []);

有什么建议吗?

您可以在临时结果中找到子数组或将该数组添加到结果集中。

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

var myArray = [
    ["revenues", 10, 20, 30],
    ["expenses", 1, 1, 1],
    ["expenses", 2, 3, 4],
    ["revenues", 5, 6, 7],
];

var result = myArray.reduce(function(acc, curr) {

    if (acc[curr[0]]) {
        acc[curr[0]] = acc[curr[0]].map(function(val, index) {

            if (index) {
                return val + curr[index];
            }
            return val
        })
    } else {
        acc[curr[0]] = curr;
    }
    return acc
}, {})

console.log(Object.values(result))