JavaScript Array reduce() Method

Yashraj - Aug 27 - - Dev Community

Hi there! In this blog, you will learn about the "reduce method" and how to use it in JavaScript. So, let's get started.

Reduce is one of the array methods in JavaScript. It takes an array as input and returns a single value. The reduce method is useful when you want to process every element of an array and update a common value based on the provided callback function.

Let's dive deeper:
Reduce takes two arguments:

  1. Callback function
  2. Starting point (initial value), let's call it "result" (*Optional)

It starts with the first element of the array, passes it to the callback function, and stores the result in "result". After processing the last element, it returns the final "result".

*Optional:

If the array is empty and no initial value is provided, reduce will throw a TypeError because there's no element to serve as the initial accumulator.

If the array has only one element and no initial value is provided, reduce returns that single element without invoking the callback.

Examples:
This examples will help you to understand how and where to use the reduce method. Feel free to ask questions in comments.

Easy:
Q. Given an array, sum its elements.

Solution using reduce method.

const arr = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumofArray = arr.reduce(
  (result, element) => result + element,
  initialValue,
);

console.log(sumofArray);
// Expected output: 10
Enter fullscreen mode Exit fullscreen mode

Explanation:
Initially, the result will be zero, as we have provided zero as the second argument. Then, for each element, it will add that element to the result, and lastly, the final result value will be returned.

Medium:

This example is taken from: https://leetcode.com/problems/flatten-deeply-nested-array/description/

Q. Given a multi-dimensional array arr and a depth n, return a flattened version of that array.

A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.

A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array is considered to be 0.

Solution with Reduce method :

function flattenArray(arr, depth) {
    if(depth===0) return arr;
    return arr.reduce((result,element) => {
       if(Array.isArray(element)&&depth>0) {
          result.push(...flattenArray(element, depth-1));
       } else {
          result.push(element); 
       }
       return result;
   }, []);
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
If the depth is zero, we don't need to do anything. Otherwise, we use recursion and the spread operator to add the elements to the result.

That's it! I hope you've learned about the reduce method well.

References :
Array.prototype.reduce() from MDN

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player