如何将n个相同长度的数组相乘?

dan*_*boy 1 javascript

我想将相同长度的数组相乘。数组的总数 ( input.length) 已知,但可以是 0 到 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
Run Code Online (Sandbox Code Playgroud)

我在 SO 上找到了通过将两个数组相互映射来相乘的解决方案,但不适用于 n 个数组。

我很感激任何提示。

Ren*_*dC5 6

如果你想将数组相乘,最好的解决方案是Array#Reduce函数

你在这里只需要像我一样引入一个函数multiplyArray来处理如何一起计算数组

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)
Run Code Online (Sandbox Code Playgroud)