Array.prototype.reduce() in JavaScript

Array.prototype.reduce() in JavaScript

This is episode three of the JavaScript Snippet Series. In Episode one, we discussed three methods of getting unique values from JavaScript. In Episode two we discussed some ways to sort arrays in JavaScript.

In this article, we will be looking at using Array.prototype.reduce() in various useful ways in JavaScript.

There are some specific terms we need to understand to be able to use the reduce() function effectively.

  • accumulator: The value of the final result.
  • reducer : The callback/function passed to the reduce function which we use to reach the final result. The callback function takes two parameters - the accumulator and the currentValue - the operation to return the accumulator is performed inside the body of the callback function. The initial value of the accumulator can be set in the second parameter passed to the reduce function.

The reduce function signature is represented below:

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

The following bullet points explain the function signature:

  • callback: the function that is called on every element of the array.

  • accumulator: this depends on the initial value. Like we mentioned above, this is also the final value returned

  • currentValue: The current value being processed.

  • index: the index or position of the current element being processed. Array indexes are 0-based.

  • array: the initial array the reduce function is applied to

  • initialValue: the value to use as the first argument when the callback function runs. If it is not defined, the callback function takes the first element and skips it.

Now let's look at various examples of using reduce in JavaScript.

Performing arithmetic on the values of an array.

const arrSum = [1, 2, 3, 4, 5, 6]

const callback = (accumulator, currentValue) => accumulator + currentValue
const result = arrSum.reduce(callback)
console.log(result)

Array Sum

Using the reduce method, the accumulator adds every element of the array together and return the result.

Fibonacci Series

You can use the reduce function to compute Fibonacci values without the need to recursion.

const fib = (n) =>{
  return Array.from({ length: n }).reduce(
    (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i)
  , []).join(",")
}

const result = fib(10)
console.log(result)

reduce 3.png

In this function, we simply declare a new array and give it a length of the supplied argument, then run the reduce function on that array.

Filtering and mapping an array

Traditionally, one way of filtering an array and then return specific values would be to use the Array.prototype.filter combined with the Array.prototype.map function.

For example, given a list of movies stars below:

const movieActors = [
  {
    name: "Greg Grunberg",
    film: "Star Wars",
  },
  {
    name: "Greg Grunberg",
    film: "Star Trek",
  },
  {
    name: "Brian George",
    film: "Star Wars",
  },
  {
    name: "Brian George",
    film: "Star Trek",
  },
  {
    name: "David Prowse",
    film: "Star Wars",
  },
  {
    name: "Mark Hamill",
    film: "Star Wars",
  },
  {
    name: "Carrie Fisher",
    film: "Star Wars",
  },
  {
    name: "Harrison Ford",
    film: "Star Wars",
  },

  {
    name: "William Shatner",
    film: "Star Trek",
  },
  {
    name: "Leonard Nimoy",
    film: "Star Trek",
  },
  {
    name: "DeForest Kelley",
    film: "Star Trek",
  },
  {
    name: "James Doohan",
    film: "Star Trek",
  },
]

if we wanted to return the names of actors that were in Star Trek we would need to do the following using map and filter

const result = movieActors
  .filter((actor) => actor.film === "Star Trek")
  .map((actor) => actor.name)
console.log(result)

As we can see in the image below, it returns the correct names including those that were in both Star Wars and Star Trek.

reduce4.png

Instead of having two different functions called on this array, we can easily use the reduce function to achieve this in one go:

const result = movieActors.reduce((names, actor) => {
  if (actor.film === "Star Trek") {
    names.push(actor.name)
  }
  return names
}, [])
console.log(result)

We can see from the image below, that this gives us exactly the result we want.

reduce4.png

That is all we have time for today. Join us next time as we discuss more JavaScript array function. Don't forget to react, comment and share this article if it was of value to you. Thank you for reading.