Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the Array method `reduce` do?

I found a very useful function reduce, and I'm using it, but I'm not sure if I understand it properly. Can anyone help me to understand this function?

Example:

var arr = [ 1, 2, 3, 4, 5, 6 ];
arr.reduce(function(p,n){
    return p + n;
}, 0);
// Output 21

This is my understanding: reduce loops through every element of the array and returns previous + current value. Ex. 0 + 1, 1 + 2 etc. In this case this function will return:

[0] - return 1
[1] - return 3
[2] - return 5
[3] - return 7
[4] - return 9
[5] - return 11

What next? Why does it give the result 21?

like image 808
Steave Avatar asked Oct 28 '15 13:10

Steave


3 Answers

Taken from here, arr.reduce() will reduce the array to a value, specified by the callback. In your case, it will basically sum the elements of the array. Steps:

  • Call function on 0,1 ( 0 is the initial value passed to .reduce() as the second argument. Return sum od 0 and 1, which is 1.
  • Call function on previous result ( which is 1 ) and next array element. This returns sum of 1 and 2, which is 3
  • Repeat until last element, which will sum up to 21
like image 140
Transcendental Avatar answered Oct 21 '22 12:10

Transcendental


reduce() method has two parameters: a callback function that is called for every element in the array and an initial value.

The callback function also has two parameters: an accumulator value and the current value.

The flow for your array ([1, 2, 3, 4, 5, 6]) is like this:

1. return 0 + 1 // 0 is the accumulator which the first time takes the initial value, 1 is the current value. The result of this becomes the accumulator for the next call, and so on..
2. return 1 + 2 // 1 - accumulator, 2 - current value
3. return 3 + 3 // 3 - accumulator, 3 - current value, etc...
4. return 6 + 4
5. return 10 + 5
6. return 15 + 6

And when reached to the end of the array, return the accumulator, which here is 21

like image 37
Valentin S. Avatar answered Oct 21 '22 12:10

Valentin S.


First of all, the name "reduce" doesn't actually reduce anything. It's a confusional/tricky naming convention you often find in programming.

reduce is a higher order function which takes two arguments:

  1. Callback function and
  2. Initial Value.

And the callback function takes four arguments:

  1. previousValue,
  2. currentValue,
  3. currentIndex,
  4. array

More often you will find the callback function takes only two arguments according to the problem we need to solve, which is Okay.

[1, 2, 3].reduce((previousValue, currentValue, currentIndex, array) => {
  // here the return statement goes...
}, initialValue);

Now let's look at a practical example. Write a program to return the sum of all the elements in an array. Please think in a as-usual way/procedure first, then we will solve the same thing with reduce. Here is the as-usual way/procedure of writing this program:

function sum(arr) {
  let sum = 0;
  for(let i = 0; i < array.length; i++) {
    sum = sum + arr[i];
  }
  return sum;
}

So, if we call sum with an array it will return the sum of it's all elements. Right?

Yeah, And we can do the same thing with reduce also. Here is the code:

[1, 2, 3, 4].reduce(function(previousValue, currentValue) {
  let result = previousValue + currentValue;
  return result;
}, 0);

It does the same thing. The reducer walks through the array element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) - until there are no more elements to add.(reference: here)

Here the previousValue is the as-usual sum and currentValue is the as-usual arr[i].

In the first iteration, there is no previousValue (return value of the previous calculation) - right? In this case, initialValue will be used as previousValue. If there is no initialValue, the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Instead of using extra variable result, you can write the program like this:

[1, 2, 3, 4].reduce(function(previousValue, currentValue) {
  previousValue += currentValue;
  return previousValue;
}, 0);

And more shortly:

[1, 2, 3, 4].reduce((previousValue, currentValue) => previousValue += currentValue, 0);

Hope you understand. Now it's your task to write a program which will find the minimum number from a non-empty array using reduce (consider all the elements in the array are positive).

Here it is:

const arr = [4, 2, 3, 1];
let result = arr.reduce((minValue, currentValue) => {
  if (currentValue < minValue) {
    minValue = currentValue;
  }
  return minValue;
}); // no initial value 😎
console.log(result);

❤️ Happy Coding ❤️

like image 20
Robin Avatar answered Oct 21 '22 11:10

Robin