2

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?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • Did you try to use json object? It work as an hash map. Your keys are "revenues" and "expenses", the value is an object with 1 : resultOne, 2: resultTwo, 3: resultThree – carmelolg Jul 26 '18 at 09:46
  • I tried to use map and reduce only. I will try that too – Leo Messi Jul 26 '18 at 09:47

2 Answers2

4

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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))
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30