I've been learning Ramda and wanted to know how to sum n-arrays by index. Below is what I was able to do with 2 arrays. How can I make this method scale?
i.e. I'd like to be able to do this: sumByIndex( arr1, arr2, ..., arrn )
Given lists x
and y
, the resultant array should yield [x0 + y0, x1 + y1, ..., xn + yn]
. So for the case of n-array, the resultant array should be [ a[0][0] + a[1][0] + ... a[n][0], a[0][1] + a[1][1] + ... a[n][1], ..., a[0][n] + a[1][n] + ... + a[n][n] ]
where a[n]
is an array as an argument at position n
.
var array1 = [1,2,3];
var array2 = [2,4,6];
var sumByIndex = R.map(R.sum);
var result = sumByIndex(R.zip(array1, array2));
$('pre').text(JSON.stringify(result, true));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.18.0/ramda.min.js"></script>
<pre></pre>