Can array.prototype.reduce () be used to process two arrays at once?

I have two arrays of the same length and I would like to somehow process both of them at once using 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

      

Of course, one would need to access the correct element from arr2

with currentIndex

, but this solution is ugly since 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 exceeds the cost of the corresponding resource in another array, for example var cost = [3, 1, 0, 0, 1]

.

Is there any nice solution for this using a function reduce()

?

+3


source to share


3 answers


Using Ramda , you can zip two lists first, then shrink it and use destructuring to retrieve the elements of the array and pass them as arguments to the callback:



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>
      

Run codeHide result


+2


source


The standard way I know to do this is to concatenate the 2 lists into a list of matching pairs ("zipping") and then shrink the combined lists:

var zipped = zip(arr1, arr2)

reduce((acc, [x, y]) => (Use x and y), 
              zipped) 

      



For implementations zip

, see this question.

(Will check the syntax when I have finished transit)

+1


source


You can do the following with pure JS;

var arr1 = [2, 3, 4, 5, 6],
    arr2 = [5, 10, 4, 9, 5],
  result = arr1.reduce((r,c,i) => (r.sum = r.sum ? r.sum + c * r[i] : c * r[i], r), arr2.slice()).sum;
console.log(result);
      

Run codeHide result


I .slice()

arr2

so as not to mutate it with a state variable, but you can still do without slicing if no loop is applied for in

to arr2

or such ...

0


source







All Articles