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.
>Solution :
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 together
const input = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
];
const multiplyArray = (arr1, arr2) => {
if(arr1.length !== arr2.length) {
throw new Error('Array have not the same length');
}
arr1.forEach((elem, index) => {
arr1[index] = elem * arr2[index]
})
return arr1
}
const output = input.reduce((acc, curr) => {
if(acc === null) return curr
return multiplyArray(acc, curr)
}, null)
console.log(output)