ES6 - Array reduce method

ES6 JavaScript

In this ES6 tutorial we are going to learn about the array reduce method. So, let's get started.

Just like the Map and Filter methods that we learned in the previous tutorials, the Reduce method also iterates over all the elements of the array and executes a reducer function on each element, passing the computed value from the previous step. Now what does that mean. Let's see that in action with the help of the following example.

Add the elements of an array using reduce

Let's say we have an array of integer values and we want to add all the elements and find the sum. To solve this problem we can run the following code.

const arr = [1,2,3,4,5];
let sum = 0;
for(let i = 0; i < arr.length; i++) {
  sum += arr[i];
console.log(sum); // 15

We can solve this problem using reduce method by writing the following code.

const arr = [1,2,3,4,5];
const sum = arr.reduce((result, currentNumber) => {
  return result + currentNumber;
}, 0);
console.log(sum); //15

Segregate odd and even numbers using reduce

Let's take another example. We have an array of integer values and we want to group all the odd numbers in one array and all the even numbers in another array. We can achieve this using the reduce method.

const arr = [1,2,3,4,5];
const segregated = arr.reduce((result, currentNumber) => {
  if (currentNumber % 2 === 0) {
    return {...result, even: [...result.even, currentNumber]};
  return {...result, odd: [..result.odd, currentNumber]};
}, {odd: [], even: []});


Thank you for reading this tutorial see you in the next tutorial. Have fun learning.