I want to multiply arrays of the same length. The total number of arrays (input.length
) is known, but it can be everything between 0 and n.
const input = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
];
const output = [1, 16, 81, 256];
// 1*1*1*1, 2*2*2*2, 3*3*3*3, 4*4*4*4
I found solutions on SO for multiplying two arrays by mapping them against each other, but not for n arrays.
I am grateful for any hints.
3
Answers
If you want to multiply arrays, the best solution would be the Array#Reduce function
You here only need to introduce a function as I did with
multiplyArray
to handle how to compute to arrays togetherYou can use Array.prototype.map() combined with Array.prototype.reduce() and Array.prototype.every() to create a function
multiplyAcrossArrays
with validation to check length of sub-arraysCode: