I have two arrays of same length and I would like to somehow process them both at once with the reduce method. Something like:
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
An option would of course be to access the correct item from arr2
using currentIndex
, but that solution is ugly as I am accessing a variable outside of the scope of the function.
My specific use case is that I have an array with resources like var resources = [2, 5, 4, 6, 2]
and I want to check if each item is higher than corresponding resource cost in another array like var cost = [3, 1, 0, 0, 1]
.
Is there some nice solution to this using the reduce()
function?