2

The answer to Javascript equivalent of Python's zip function shows a neat way of taking any number of arrays, and "zipping" them into a merged array in a single statement.

zip= rows=>rows[0].map((_,c)=>rows.map(row=>row[c]))

This question Javascript - Sum two arrays in single iteration shows a similar idea, but summing the entries as they're zipped up.

I'm wondering how to combine the two techniques - so given an unknown number of arrays:

[
  [1,2,3],
  [1,2,3],
  [1,2,3]
]

... the result is [3, 6, 9], ie the sum of the first elements, the second and so forth. For the sake of simplicity, assume each array contains the same number of items.

Community
  • 1
  • 1
Party Ark
  • 1,061
  • 9
  • 20

4 Answers4

0

First transpose the arrays, so the columns become rows and viceaversa. After that simply call the reduce function.

The first version of the code is mostly typescript for brevity. The second version is JavaScript.

Note that ES5 map and reduce functions are only available on IE9 and higher.

var numbers = [[1,2,3],[1,2,3],[1,2,3]]

// TypeScript

var colSums = numbers[0].map(function(col, i) { 
  return numbers.map((row) => row[i]).reduce((a,b) => a + b );
});

// JavaScript

/*var colSums = numbers[0].map(function(col, i) {
  return numbers.map(function(row) {
    return row[i];
  }).reduce(function(a,b) {
    return a + b;
  });
});*/
document.getElementById("col-sums").innerHTML = colSums;
<p id="col-sums"></p>
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

I think I have it - this answer was helpful - we can extend the original zipping method thus:

zip = rows => rows[0].map((_,c) => rows.map(row=>row[c]).reduce((a,b) => a+b,0))
Community
  • 1
  • 1
Party Ark
  • 1,061
  • 9
  • 20
0

No need for map, map, reduce, two maps will get you there:

Quick Demo

var m = [
  [1,2,3],
  [1,2,3],
  [1,2,3]
];

var total = m.map(function(arr, i) {
  var count = 0;
  return arr.map(function(el, idx) {
    return count += m[idx][i];
  })
}).pop()
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

Similar to other answers, it just doesn't have to be so complicated:

numbers = [[1,2,3],[1,2,3],[1,2,3]];

var result = numbers[0].map(function(_, i) { 
  return numbers.reduce(function(prev, row) {
    return row[i] + prev;
  }, 0);
});

console.log(result);
Amit
  • 45,440
  • 9
  • 78
  • 110