šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Javascript reduce array method explained

I find myself using the JS Array.reduce() quite often, especially when I write answers for Javascript interview questions. I think it's one of the most flexible and underrated methods in Javascript.

Let's see how the reduce() method works.

If we want to calculate the sum of the following array:

const numbers = [12, 6, 8, 41]

We can do that using the Javascript reduce() function:

const sum = numbers.reduce((s, item) => {
  return s + item
}, 0)
// sum = 67

The signature of the reduce method is as follows:

array.reduce((previousValue, currentValue) => {
    // code here
}, initialValue)

The reduce() array executes a "reducer" function on each element of the array in order, passing the return value from the previous reducer function call to the next reducer call.

What the reducer function does is try to reduce an array to a value. Therefore the name.

So, in the above case the call order will be like this:

const numbers = [12, 6, 8, 41]

const sum = numbers.reduce((s, item) => {
  return s + item
}, 0)

// step 1 
reduce((0 /* initial value */ , numbers[0]) => {
    return 0 + 12
}

// step 2 
reduce((12 /* previous value */ , numbers[1]) => {
    return 12 + 6
}

// step 3 
reduce((18 /* previous value */ , numbers[2]) => {
    return 18 + 8
}

// step 4 
reduce((26 /* previous value */ , numbers[3]) => {
    return 26 + 41
}

Omitting initial value argument

The initialValue is optional. If not provided it takes the value of the first element of the array.

So, in our case, if we don't provide 0 as the initialValue we will get:

const numbers = [12, 6, 8, 41]
const sum = numbers.reduce((s, item) => {
    // s = array[0]
    // item = array[1]
})

Returning arrays from the reduce() method

Keep in mind that when we say "reducing an array to a value" that value can also be an array.

So, if we want to extract the even numbers we can write:

const numbers = [12, 6, 8, 41]
const evenNums = numbers.reduce((evenArr, item) => {
    if (item % 2 == 0) {
        evenArr.push(item)
    }
    return evenArr
}, [])

// note the passing of [] as the initial value
// evenNums = [12, 6, 8]

The reduce callback function - getting the current index and array

The callback function actually has 4 arguments. The full format of the function looks like this:

Array.reduce((previousValue, currentValue, currentIndex, array) => {
    // code here 
}, initialValue)

The last two parameters are optional:

  • currentIndex: gets the current index being iterated through; it starts from zero
  • array: this will return the entire array, which can be useful if you plan to manipulate the array using reduce

So, if we look at the initial sum example:

const numbers = [12, 6, 8, 41]
const sum = numbers.reduce(
    (s, item , currentIndex , array) => {
        return s + item
    }, 
0)

If we use these parameters in the initial sum example we will get the below stack trace:

s item currentIndex array
First call 0 12 0 [12, 6, 8, 41]
Second call 12 6 1 [12, 6, 8, 41]
Third call 18 8 2 [12, 6, 8, 41]
Fourth call 26 41 3 [12, 6, 8, 41]

And speaking Javascript arrays I've written also this article about how to find and replace an object in an array.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *