title: Sum array of arrays (matrix) vertically efficiently/elegantly
body: <p>In Javascript, if I have an array of arrays representing a matrix, say</p>
  <pre><code>x = [
      [1,2,3,4],
      [5,6,7,8],
      [9,10,11,12]
  ];
  </code></pre>
  <p>summing it &quot;horizontally&quot; is easy and can be done like</p>
  <pre><code>x.map(function(y){
    return y.reduce(function(a,b){
        return a+b;
    });
  });
  </code></pre>
  <p>or</p>
  <pre><code>x.map(y =&gt; y.reduce((a, b) =&gt; a+b));
  </code></pre>
  <p>Now I would like to compute the &quot;vertical&quot; sum, which can be done</p>
  <pre><code>x.reduce(function(a, b){
      return a.map(function(v,i){
          return v+b[i];
      });
  });
  </code></pre>
  <p>or</p>
  <pre><code>x.reduce((a, b) =&gt; a.map((v,i) =&gt; v+b[i]));
  </code></pre>
  <p>But I am not happy with this version and I wish there were something nicer, more elegant and more straightforward. Maybe an easy way to transpose the matrix beforehand? anyone?</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const x = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
  ];
  
  const a = x.map((y) =&gt; y.reduce((a, b) =&gt; a + b));
  const b = x.reduce((a, b) =&gt; a.map((v, i) =&gt; v + b[i]));
  const c = x.flat().reduce((a , b) =&gt; a + b)
  
  console.log('Summing horizontally: '  + JSON.stringify(a));
  console.log('Summing vertically: ' + JSON.stringify(b));
  console.log('Summing whole array: ' + JSON.stringify(c));</code></pre>
  </div>
  </div>
  </p>
  <p>Note that I asked a similar question a few days ago (<a href="https://stackoverflow.com/questions/32019544/combining-two-arrays-of-same-size-and-returns-sum?noredirect=1#comment51941758_32019544">link</a>) but that lacked the bigger picture.</p>