DEV Community

Vishal Vansjariya
Vishal Vansjariya

Posted on

Supercharge Your JavaScript with the reduce() Method

Poster

What is reduce()?

The reduce() method is a higher-order function in JavaScript that is used to reduce an array to a single value. It works by executing a provided function on each element of the array and accumulating the results into a single value. The signature of the reduce() method is as follows:

array.reduce(callback, [initialValue])
Enter fullscreen mode Exit fullscreen mode

The callback parameter is the function to be executed on each element of the array, and it takes four arguments:

  1. accumulator: The accumulator accumulates the callback's return values. It is the accumulated value previously returned by the callback. If the initialValue is provided, then the accumulator will be initialized with the initialValue. Otherwise, it will be initialized with the first element of the array, and the callback will be executed on the second element onwards.

  2. currentValue: The current element being processed in the array.

  3. currentIndex (optional): The index of the current element being processed in the array.

  4. array (optional): The array being processed.

The initialValue parameter is optional, and it is used to initialize the accumulator. If it is not provided, then the first element of the array will be used as the initial value, and the callback will be executed on the second element onwards.

How to use reduce()?

To use reduce(), you need to define a callback function that takes in the accumulator and the current value and returns a new value that will be added to the accumulator. Here's an example of how to use reduce() to sum an array of numbers:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

In this example, the callback function takes in the accumulator and the currentValue and returns the sum of the two. The reduce() method is called on the numbers array, and the initial value of the accumulator is set to 0. The result of the reduce() method is the sum of all the numbers in the array, which is 15.

Another Example

Here’s another example of how to use reduce() to find the maximum number in an array:

const numbers = [10, 20, 30, 40, 50];

const max = numbers.reduce((accumulator, currentValue) => {
  if (currentValue > accumulator) {
    return currentValue;
  } else {
    return accumulator;
  }
}, numbers[0]);

console.log(max); // Output: 50
Enter fullscreen mode Exit fullscreen mode

In this example, the callback function takes in the accumulator and the currentValue and returns the maximum of the two. The reduce() method is called on the numbers array, and the initial value of the accumulator is set to the first element of the array. The result of the reduce() method is the maximum number in the array, which is 50.

The Initial Value

The initialValue parameter is an optional argument that can be used to initialize the value of the accumulator. If it is not provided, then the first element of the array is used as the initial value of the accumulator, and the reduce() method is executed on the second element of the array onwards.

Here’s an example of using the initialValue parameter to initialize the accumulator to 100:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 100);

console.log(sum); // Output: 115
Enter fullscreen mode Exit fullscreen mode

In this example, the reduce() method is called on the numbers array with an initial value of 100 for the accumulator. The result of the reduce() method is the sum of all the numbers in the array, plus the initial value of 100.

The Index and Array Parameters

The reduce() method also provides two optional parameters to the callback function: the currentIndex and the array parameters.

The currentIndex parameter is the index of the current element being processed in the array.

The array parameter is a reference to the array that the reduce() method is being called on.

Here’s an example of using the currentIndex and array parameters to calculate the sum of the even-indexed elements of an array:

const numbers = [1, 2, 3, 4, 5];

const evenSum = numbers.reduce((accumulator, currentValue, currentIndex) => {
  if (currentIndex % 2 === 0) {
    return accumulator + currentValue;
  } else {
    return accumulator;
  }
}, 0);

console.log(evenSum); // Output: 9
Enter fullscreen mode Exit fullscreen mode

In this example, the callback function takes in the accumulator, the currentValue, and the currentIndex. If the currentIndex is even, then the currentValue is added to the accumulator. Otherwise, the accumulator is returned without any modification. The reduce() method is called on the numbers array with an initial value of 0 for the accumulator. The result of the reduce() method is the sum of all the even-indexed elements of the array.

Chaining the reduce() Method

The reduce() method can be chained with other array methods to perform more complex operations on the array. Here's an example of chaining the map() method with the reduce() method to calculate the sum of the squares of the even numbers in an array:

const numbers = [1, 2, 3, 4, 5];

const evenSquaresSum = numbers
  .filter((number) => number % 2 === 0)
  .map((number) => number ** 2)
  .reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
  }, 0);

console.log(evenSquaresSum); // Output: 20
Enter fullscreen mode Exit fullscreen mode

In this example, the filter() method is used to select only the even numbers in the numbers array, the map() method is used to square each of the even numbers, and the reduce() method is used to calculate the sum of the squared even numbers. The result of the reduce() method is the sum of the squares of the even numbers in the array.

Here are a few more examples of using the reduce() method.

Example 1: Calculating the Product of an Array

The reduce() method can be used to calculate the product of an array of numbers. Here's an example:

const numbers = [1, 2, 3, 4, 5];

const product = numbers.reduce((accumulator, currentValue) => {
  return accumulator * currentValue;
}, 1);

console.log(product); // Output: 120
Enter fullscreen mode Exit fullscreen mode

In this example, the reduce() method is used to calculate the product of the numbers in the numbers array. The initial value of the accumulator is 1, and the callback function multiplies the accumulator by each element of the array to arrive at the final product of 1 * 2 * 3 * 4 * 5 = 120.

Example 2: Flattening an Array of Arrays

const arrays = [[1, 2], [3, 4], [5, 6]];

const flattenedArray = arrays.reduce((accumulator, currentValue) => {
  return accumulator.concat(currentValue);
}, []);

console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

In this example, the reduce() method is used to flatten the arrays array into a single array. The initial value of the accumulator is an empty array, and the callback function concatenates the accumulator with each sub-array of the arrays array to arrive at the final flattened array [1, 2, 3, 4, 5, 6].

Example 3: Counting the Occurrences of Values in an Array

The reduce() method can also be used to count the occurrences of values in an array. Here's an example:

const words = ['hello', 'world', 'hello', 'goodbye', 'world'];

const wordCount = words.reduce((accumulator, currentValue) => {
  if (currentValue in accumulator) {
    accumulator[currentValue]++;
  } else {
    accumulator[currentValue] = 1;
  }
  return accumulator;
}, {});

console.log(wordCount); // Output: {hello: 2, world: 2, goodbye: 1}
Enter fullscreen mode Exit fullscreen mode

In this example, the reduce() method is used to count the occurrences of each word in the words array. The initial value of the accumulator is an empty object, and the callback function checks whether the current word is already a key in the accumulator object. If it is, the function increments the value associated with that key. If it is not, the function adds a new key to the accumulator with a value of 1. The final result is an object that shows the count of each word in the words array.

Conclusion

The reduce() higher-order function in JavaScript is a powerful tool for reducing an array to a single value. By providing a callback function and an optional initial value, you can perform a wide range of operations on an array, from simple summations to more complex calculations. The reduce() method can also be chained with other array methods to perform more complex operations on arrays. I hope this article has helped you to understand the reduce() method and how it can be used in your JavaScript code.


If it’s helpful for you 💛
Buy Me Coffee

Top comments (0)