Steave
Steave

Reputation: 137

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?

Upvotes: 8

Views: 12627

Answers (6)

Robin
Robin

Reputation: 5427

First of all, the name "reduce" doesn't actually reduce anything. It's a confusional/tricky naming convention you often find in programming. Although for better understanding you can assume - it takes lots of values and reduce them into a single value and return.

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 ❤️

Upvotes: 3

Manoj Swami
Manoj Swami

Reputation: 149

All of the above answers have explained the arr.reduce() for addition only, what if I want to perform something else with the reduce, like subtraction, multiplication etc.

In that case how the reduce will perform in background?

Here is the detailed explanation to the answer:

function reduce(array, iterator, initialValue) {
    const isInitialValueDefined = typeof initialValue !== "undefined";
    if (!isInitialValueDefined && array.length === 0) {
        throw new TypeError("Reduce of empty array with no initial value");
    }
    let acc = isInitialValueDefined ? initialValue : array[0];
    for (let i = isInitialValueDefined ? 0 : 1; i < array.length; i++) {
        acc = iterator(acc, array[i], i, array);
    }
    return acc;
}

console.log(reduce([1, 2, 3, 4], (a, i) => a + i)); // => 10
console.log(reduce([1, 2, 3, 4], (a, i) => a * i, 1)); // => 24
console.log(reduce([], (a, i) => a + i)); // => TypeError

reduce() is a function which takes two arguments:

  1. Callback function
  2. Initial Value

Callback function takes four arguments:

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

Most of the time you will find that callback function takes 2 arguments only.

Upvotes: 0

Santosh Singh
Santosh Singh

Reputation: 1272

Reduce Function: Reduce function does not reduce anything. Reduce is the function to take all the elements of an array and come out with a single value out of an array. enter image description here

Upvotes: 0

bvdb
bvdb

Reputation: 24770

To get a better understanding of how reduce works, use the following sum(a,b) function which logs a text like a+b=c for each operation it performs.

function sum(a,b) { 
  const c = a + b;
  console.log(`${a} + ${b} => ${c}`)
  return c;
}

const arr = [1,2,4,8];
const result = arr.reduce(sum);
console.log(`result=${result}`)

This prints 1+2=>3, 3+4=>7, 7+8=>15 and finally result=15.

There are 2 corner cases:

  • just 1 element --> just returns the element.
  • no elements, empty arrays --> throws an error.

A possible solution, is to use an initializer.

initializer

Upvotes: 1

Valentin S.
Valentin S.

Reputation: 504

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

Upvotes: 10

Transcendental
Transcendental

Reputation: 981

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

Upvotes: 14

Related Questions