Home > Mobile >  matrix (array of arrays|bidimensional array) sum without loops. There are a better way?
matrix (array of arrays|bidimensional array) sum without loops. There are a better way?

Time:10-12

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!.

CodePudding user response:

"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

CodePudding user response:

You can use reduce method and I think it's more readable

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



var result = multArray.reduce(function (a, b) { return a.concat(b) }) // flatten array
    .reduce(function (a, b) { return a   b });

var result2 = multArray2.reduce(function (a, b) { return a.concat(b) }) // flatten array
    .reduce(function (a, b) { return a   b });

console.log(result   result2);


  • Related