javascript - 我可以使用 array.prototype.reduce() 一次处理两个数组吗?

标签 javascript arrays

我有两个长度相同的数组,我想以某种方式使用 reduce 方法同时处理它们。像这样的东西:

var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
    /* here I would like to multiply item from arr1 by the item from arr2 at the same index */
    return sumOfProducts + item * secondArrayItem;  
}, 0, arr2)
console.log(productSum);  // 131

一个选项当然是使用 currentIndexarr2 访问正确的项目,但是这个解决方案很难看,因为我正在访问范围之外的变量功能。

我的具体用例是我有一个数组,其中包含 var resources = [2, 5, 4, 6, 2] 之类的资源,我想检查每个项目是否高于相应的资源成本在另一个数组中,例如 var cost = [3, 1, 0, 0, 1]

是否有使用 reduce() 函数的一些很好的解决方案?

最佳答案

使用 Ramda您可以先压缩两个列表,然后缩减它并使用解构来提取数组元素并将它们作为参数传递给回调:

const reduceTwo = (callback, initialValue, arr1, arr2) =>
  R.reduce((acc, [x, y]) => callback(acc, x, y), initialValue, R.zip(arr1, arr2));

const arr1 = [2, 3, 4, 5, 6];
const arr2 = [5, 10, 4, 9, 5];
console.log(reduceTwo((acc, x, y) => acc + x * y, 0, arr1, arr2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

关于javascript - 我可以使用 array.prototype.reduce() 一次处理两个数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44400091/

相关文章:

mysql - C - 将数组作为参数传递并更改大小和内容

javascript - 在单元格过滤器突出显示上保留链接标记

javascript - 使用条件angularjs设置默认值

javascript - 是否可以创建一个作为另一个对象的子集的对象,而不会丢失 JavaScript 中的引用?

javascript - 在 MongoDB 中获取查询外的数据

javascript - string.match() 返回字符串而不是数组

javascript - 如何在没有 TestUtils.findAllInRenderedTree 的情况下遍历包括 DOM 组件在内的所有 React 组件?

c - 字符串数组和 Gnome 排序

Php - 通知 : Undefined offset 10?

javascript - 在二维数组 javascript 中的 30 个变量之后创建 <br> 行