Using reduce() method in JavaScript

Using reduce() method in JavaScript

Introduction

JavaScript array has many iteration methods like, map(), filter(), reduce(). I will be explaining about the reduce() method in this article.

What is reduce() method?

The reduce function is a functional programming technique with which you can solve any array processing problem with it. According to MDN, the reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

We can say, the reduce() method executes a callback function which you will specify what needs to perform on each element of an array, which will result a single output value.

Prerequisite

  • You must understand how an array works.

  • You must have the basic knowledge about ES6 Arrow function.

The reduce() method Syntax:


arr.reduce(callback( accumulator, currentValue, [, index[, array]])[, initialValue]);

The callback() function: is the function to execute on each element in the array the first value element excluded if no initial value is provided.

The callback() function takes four arguments:

  • Accumulator: accumulates the callback's function returned values from the previous iteration.

  • Current value: The current value is the element being processed in the array.

  • Current index: The current index is the index of the element in the array being processed. Starts from index 0 if no initial value is provided, otherwise, it starts from 1.

  • Source array: The source array is the array which is being called upon.

Initial value: The initial value is a value used as the first argument to the first call of the function. If the initial value is not provided, then the first element in the array will be the initial value and skipped as the current value i.e the accumulator will be the initial value and skipped as the current value.

Note: if the array is empty and no initial value id provided a TypeError will be thrown.

Return value: The return value will depend on your reduction.

How the reduce() method works?

Reducing an array to a single value

Let's take, for example, we have an array arr = [1, 2, 3, 5, 62, 37, 28] to return sum all the elements in an array.

Solution

We can solve this question using two ways, using the initial value or no initial value.

Using the initial value

const arr = [1,2,3,5,62,37,28]

let sum = arr.reduce((acc, currentValue) => (acc + currentValue), 0)

console.log(sum) // returns 138

If we walk through every iteration in the above reduce method it looks like this:

IterationaccumulatorcurrentValuecurrentIndexarrayreturn value
first call010[1, 2, 3, 5, 62, 37, 28]1
second call121[1, 2, 3, 5, 62, 37, 28]3
third call332[1, 2, 3, 5, 62, 37, 28]6
fourth call653[1, 2, 3, 5, 62, 37, 28]11
fifth call11624[1, 2, 3, 5, 62, 37, 28]73
sixth call73375[1, 2, 3, 5, 62, 37, 28]110
seventh call110286[1, 2, 3, 5, 62, 37, 28]138

Without the initial value

const arr = [1,2,3,5,62,37,28]

let sum = arr.reduce((acc, currentValue) => (acc + currentValue))

console.log(sum) // returns 138
IterationaccumulatorcurrentValuecurrentIndexarrayreturn value
first call121[1, 2, 3, 5, 62, 37, 28]3
second call332[1, 2, 3, 5, 62, 37, 28]6
third call653[1, 2, 3, 5, 62, 37, 28]11
fourth call11624[1, 2, 3, 5, 62, 37, 28]73
fifth call73375[1, 2, 3, 5, 62, 37, 28]110
sixth call110376[1, 2, 3, 5, 62, 37, 28]138

Remove duplicates from an array

For example, we have an array arr = [ 'f', 'o', 'd', 'e', 'o', 'e', 'q', 'j', 'o', 'd' ,'p', 's', 'j', 'd', 'g', 'e'] and we are to return a new array with no duplicate of element.

Solution:

const arr = ['f', 'o', 'd', 'e', 'o', 'e', 'q', 'j', 'o', 'd', 'p', 's', 'j', 'd', 'g', 'e']
let newArray = arr.reduce((acc, currentValue) => {
  if (acc.indexOf(currentValue) === -1) {
    acc.push(currentValue)
  }
  return acc
},
  [])
// An initial value must be provided since we are storing elements
console.log(newArray) // returns [ 'f', 'o', 'd', 'e', 'q', 'j', 'p', 's', 'g' ]

Another approach is using the SET method to solve this question Note: we have used the reduce() method to return a single output value and an array, we can also use it to return an object.

Hope this is a useful explanation of the reduce() method in JavaScript. Give it a try if you are not using it already.