JavaScript Array reduce() Method

The reduce function applies a reducer function to each item in the array, ultimately condensing it into a single accumulated result. This method is built into JavaScript. The user is responsible for defining the reducer function that operates on each element within the array. Additionally, it can take an optional initial value and processes the elements from left to right, transforming the array into a singular outcome. This method is commonly used for tasks such as finding the maximum value in an array, the minimum value in an array, and calculating the total sum of an array.

Reducer Function

The reducer function is the user-implemented code. It uses the following four arguments to perform its task:

  • Accumulator: It stores the accumulated result from previous iterations of the callback.
  • Current Value: It is the current value that is being processed.
  • Current Index: It is an optional value. The index of the current element is the value of the current index.
  • Source array: It is an optional value. The original array defined by the user for implementing the reduce
  • Syntax

    Example
    
    arr.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue);
    

    Parameter

callback: This refers to the function that is performed on every element of the array, omitting the first one, in the absence of an initialValue. In such cases, the operation commences from the second element.

The callback function undertakes the following four arguments:

  • accumulator: It accumulates the return values of the callback function, the values returned from the last call of the function.
  • currentValue: It is the value of the current element, which is being processed.
  • currentIndex: It is an optional argument that holds the index value of the current element that is being processed. If we provide the initial value, indexing will begin from 0. Else from 1.
  • array: It is also optional, which carries the elements on which the reduce will work.
  • initialValue: It is the first argument value used in the first invocation of the callback function.
  • Return

It returns a single value as an output.

Points to note:

  • If we do not provide the initial value, the callback function will start its execution with index as 1, where it will skip the first index. Although if initialValue is provided, execution will begin from 0.
  • In case of an empty array with no initialValue supplied, it will throw a TypeError .
  • If the array is empty but initialValue is provided then reduce will return the initialValue . If the array contains one element but no initialValue is supplied, that element will be returned without invoking the callback

Therefore, it is both advisable and beneficial to specify the starting value.

JavaScript Array reduce Method Examples:

Let’s explore a few examples to gain a clearer understanding:

Example 1: A Simple example to sum up the array.

Below is a straightforward illustration that demonstrates how to calculate the total of the elements within an array and present the resulting output.

Example

Example

var arr=[2,3,1,5];  

var a=arr.reduce(function (accumulator,currentValue) {  

    return accumulator+currentValue;  

    },0);  

console.log("The sum of the array elements is "+a);

Output:

Output

The sum of the array elements is 11

Explanation:

In the code provided above, a variable referred to as arr was declared utilizing the var keyword. We assigned an array to this variable. In this instance, we employed the reduce method, which executes the reducer function on each element within the array. This process yields a singular output value. The method accepts two parameters: accumulator and currentValue. In our implementation, we specified 0 as the starting value.

Example 2: Displaying the difference between the array elements

Below is an illustration demonstrating how to calculate the difference between elements in an array utilizing the reduce method. The operation begins with the first element serving as the initial value.

Example

Example

var a=[30,15,5];  

console.log("The difference of the array elements is ");  

console.log(a.reduce(reducer_func));  

function reducer_func(net,n){  

return net-n;  

};

Output:

Output

The difference of the array elements is 

10

Explanation:

In the code presented above, we declare a variable called a with the var keyword. We employed the reduce method to calculate the difference between the elements of the array. The reduce method applies a reducer function to every element in the array, ultimately condensing it into a single value.

In this context, net serves as the accumulator. The variable n represents the element that is currently under consideration. At each iteration, the expression net - n calculates the difference by subtracting the current element from the accumulator, resulting in a value of 10.

Example 3: Totalling the elements of an array using an arrow function

Below is an illustration of how to calculate the sum of array elements utilizing the arrow function syntax.

Example

Example

let myValue = [3, 2, 5, 1, 7];  

let totalValue = myValue.reduce(  

(accumulator,currentValue) => accumulator + currentValue, 0);  

console.log("The total of the array elements comes out to be "+ totalValue);

Output:

Output

The total of the array elements comes out to be 18

Explanation:

In the preceding example, we initialized a variable called myValue using the let keyword and assigned it an array containing numerical values. This array, myValue, consists of five distinct numbers. We then utilized the .reduce method on each element within the array. In this context, the parameter accumulator serves to maintain the cumulative total, while currentValue represents the specific element of the array that is currently being processed. The 0 we provide after the function denotes the initial value for the accumulator. Consequently, the accumulator begins at 0; thus, the calculation for the first element results in 0 + 3 = 3, for the second element it becomes 3 + 2 = 5, and this process continues until the reduce method has summed all elements of the array.

Example 4: Array with a single value only

In the following example, we will examine the outcome when the array consists of just one value.

Example

Example

let myElem=[3]; //Array with one element.  

let totalCalc= myElem.reduce(  

(accumulator,currentValue)=>accumulator+currentValue);  

console.log("The total of the array elements comes out to be "+ totalCalc);

Output:

Output

The total of the array elements comes out to be 3

Explanation:

In the previous illustration, we establish a variable called myElem utilizing the let keyword. This variable is assigned an array that contains only one element. In this context, the accumulator maintains the ongoing total, while the variable currentValue represents the current item from the array. It is important to note that if we do not specify a starting value, the first element of the array will serve as the initial accumulator.

In the code we are examining, we have not assigned any starting value. As a result, the accumulator is equal to 3. There is no additional element to operate on. Consequently, in the preceding code, the callback function does not execute, and the .reduce method merely yields 3. Thus, the sum of the elements in the array amounts to 3.

In cases where an array contains a single element and no initialValue is provided, the callback function will not be triggered, and the element itself will be returned without any alterations.

Example 5: Counting using the reduce method

In this instance, we will tally the characters of the string and produce an object that contains the count of each letter for the specified string.

Example

Example

const myFruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'grape'];

const fruitCounts = myFruits.reduce((accumulator, currentFruit) => {

  // If the fruit already exists in the accumulator object, increment its count.

  // Otherwise, initialize its count to 1.

  accumulator[currentFruit] = (accumulator[currentFruit] || 0) + 1;

  return accumulator; // Return the updated accumulator for the next iteration.

}, {}); // Initialize the accumulator as an empty object.



console.log(fruitCounts);

// Expected output: { apple: 2, banana: 2, orange: 1, grape: 1 }

Output:

Output

{ apple: 2, banana: 2, orange: 1, grape: 1 }

Explanation:

In the code provided above, we declared a variable called myFruits using the var keyword. We then utilized the reduce method on the myFruits array. The reduce method iteratively processes each element of the array, one at a time. In this case, the accumulator is represented as an object. The empty object at the conclusion serves to initialize the accumulator as a blank object.

Within the reducer function, the expression accumulator[currentFruit] serves to monitor how many times each type of fruit appears. In this context, (accumulator[currentFruit] || 0) is utilized to determine if there is an existing count for the fruit. If a count exists, it retrieves that value; if not, it defaults to 0. Subsequently, we increment the count for the current fruit by adding +1.

Example 6: Grouping items using the reduce method

In this demonstration, we will categorize an array of objects based on a specific property by employing the reduce method.

Example

Example

const myProducts = [

  { id: 1, name: 'Laptop', category: 'Electronics' },

  { id: 2, name: 'Mouse', category: 'Electronics' },

  { id: 3, name: 'T-shirt', category: 'Apparel' },

  { id: 4, name: 'Jeans', category: 'Apparel' },

  { id: 5, name: 'Keyboard', category: 'Electronics' },

  { id: 6, name: 'Hat', category: 'Apparel' }

];



const groupedProducts = myProducts.reduce((accumulator, product) => {

  const category = product.category;

  if (!accumulator[category]) {

    accumulator[category] = []; // Initialize an empty array for the category if it doesn't exist

  }

  accumulator[category].push(product); // Add the current product to its respective category array

  return accumulator; // Return the updated accumulator for the next iteration

}, {}); // The initial value for the accumulator is an empty object



console.log(groupedProducts);

Output:

Output

{

  Electronics: [

    { id: 1, name: 'Laptop', category: 'Electronics' },

    { id: 2, name: 'Mouse', category: 'Electronics' },

    { id: 5, name: 'Keyboard', category: 'Electronics' }

  ],

  Apparel: [

    { id: 3, name: 'T-shirt', category: 'Apparel' },

    { id: 4, name: 'Jeans', category: 'Apparel' },

    { id: 6, name: 'Hat', category: 'Apparel' }

  ]

}

Explanation:

In the code above, a variable called myProduct is declared using const. The reduce function iterates through each element of the array, handling them one at a time. In this context, the accumulator is an object that organizes the products based on their categories. The initial value of the accumulator is represented by the empty object we created. In this implementation, we categorize the products within an object, where each key corresponds to a specific category, and the associated value is an array containing the products belonging to that category.

Conclusion:

In JavaScript, the Array reduce function is one of the inherent methods that applies a user-defined reducer callback function to every element in the array. This allows for the aggregation of the array elements into a singular output value. This article thoroughly explores the array reduce method, accompanied by a variety of examples, and addresses some commonly asked questions. The array reduce method represents a significant concept in JavaScript.

FAQs:

Below are several commonly asked questions:

  1. What is the purpose of the reduce function in JavaScript?

The reduce method serves the purpose of transforming an array into a singular value. This resulting value can take the form of a number, an object, another array, or any other type of data.

  1. In JavaScript, what is the operational mechanism of a reduce function?

In JavaScript, the reduce method employs a callback function. This callback receives two arguments: an accumulator and the current element from the array. The method iterates over every element in the array, applying the callback to each element and continually updating the accumulator. After processing all elements, it returns the ultimate value stored in the accumulator.

  1. What parameters does the reduce function take?

In JavaScript, the reduce method takes a callback function as its initial argument.

Accumulator: This component monitors the outcome produced by the callback function.

Current Value: This refers to the specific element within the array that is presently undergoing processing.

Current Index (optional): This is an optional parameter that indicates the location of the current item within the array.

Source Array (optional): The source array was utilized, and the array reduce function was invoked on it.

  1. Is it possible to employ the reduce function to convert an array into an object?

Absolutely, we can achieve this. The reduce function is capable of transforming an array into an object by aggregating key-value pairs.

  1. In what ways can the initial values in the reduce function be managed?

To manage initial values within the reduce function, it is possible to specify a starting value as the second argument. When a starting value is supplied, the accumulator will initiate with that specified value. Conversely, if a starting value is not given, the first element of the array will serve as the initial accumulator, and the iteration will commence with the second element of the array.

Input Required

This code uses input(). Please provide values below: