0

I was thinking on a way to make matrix sum without have to use loops and I realize use Array.prototype.map() is a good way.

var multArray = [[1,2,3,4,5],[6,7,8,9,10]];
var multArray2=[[1,2,3,4,5],[6,7,8,9,10]];
total   =  multArray.map((array, arrayIndex) => array.map((value, index) => value + multArray2[arrayIndex][index]));
console.log(total);

Do you know if there are a better or short way?

Thanks!.

MiguelMLR9
  • 276
  • 2
  • 2

2 Answers2

0

"Better" is subjective, but you can do something like this:

var multArray = [[1,2,3,4,5],[6,7,8,9,10]];
var multArray2=[[1,2,3,4,5],[6,7,8,9,10]];
console.log(
  [...Array(multArray.length).keys()].map(
     f => [...Array(multArray[f].length).keys()].map(
        s => multArray[f][s] + multArray2[f][s]
     )
  )
)

But IMO your one is more readable

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
0

I think a simple for loop is the most explicit in terms of clearly showing what is happening.

const multArray = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],];
const multArray2 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],];

const total = [];

for (let i = 0; i < multArray.length; i++) {
  total[i] = [];
  for (let j = 0; j < multArray[i].length; j++) {
    total[i][j] = multArray[i][j] + multArray2[i][j];
  }
}

console.log(total);

But if you really don't want to you could define some utility functions and chain them.

const multArray = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],];
const multArray2 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],];

const zip = (a, b) => a.map((k, i) => [k, b[i]]);
const sum = (arr) => arr.reduce((a, b) => a + b, 0);

const total = zip(multArray, multArray2).map((c) => zip(...c).map(sum));

console.log(total);

A real advantage can be gained by redefining the zip() function to accept any number of parameters and thus allowing you to total any number of arrays by simply passing them all to the initial zip call (and avoiding explicitly writing nested loops for each additional array).

const multArray = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],];
const multArray2 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],];
const multArray3 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10],];

const zip = (...rows) => [...rows[0].keys()].map((k) => rows.map((row) => row[k]));
const sum = (arr) => arr.reduce((a, b) => a + b, 0);

const sum_mult_arrays = (...arrs) => zip(...arrs).map((c) => zip(...c).map(sum));

const total = sum_mult_arrays(multArray, multArray2, multArray3);

console.log(total);

See Javascript equivalent of Python's zip function for a lot of discussion around zipping.

pilchard
  • 12,414
  • 5
  • 11
  • 23