如何实现n个等长数组的对应元素相乘?
多等长数组对应元素相乘的实现方案
边界情况处理
- 若输入的数组集合
input为空,直接返回空数组 - 若子数组长度为0,同样返回空数组
核心实现方法
方法一:按索引遍历+累积乘积
以第一个数组的长度为基准,遍历每个元素索引,对所有数组在该索引位置的元素执行累积相乘:
const multiplyArrays = (input) => { if (!input.length) return []; const subArrLength = input[0].length; if (subArrLength === 0) return []; return input[0].map((_, index) => { return input.reduce((product, currentArr) => product * currentArr[index], 1); }); }; // 测试示例 const input = [ [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4] ]; console.log(multiplyArrays(input)); // 输出: [1, 16, 81, 256]
代码说明:
input[0].map:利用第一个数组的长度确定需要处理的元素位置(所有数组等长),仅保留索引用于后续操作input.reduce:遍历所有数组,将每个数组对应索引的元素乘到累积乘积中,初始值设为1(乘法单位元,保证首次相乘逻辑正确)
方法二:转置数组后求子数组乘积
先将原数组集合转置(把列转为行),再对每个转置后的子数组计算元素乘积:
const multiplyArrays = (input) => { if (!input.length) return []; // 转置数组:将各数组的对应位置元素组成新数组 const transposed = input[0].map((_, colIndex) => { return input.map(row => row[colIndex]); }); // 对每个转置后的子数组计算乘积 return transposed.map(subArr => subArr.reduce((total, num) => total * num, 1)); };
代码说明:
- 转置操作把原数组中同一位置的元素聚合到一个子数组中,后续只需对每个子数组执行乘积计算即可
- 逻辑更直观,但转置会生成新的数组集合,内存占用略高于方法一
内容的提问来源于stack exchange,提问作者dan_boy
相关产品推荐
相关产品推荐

