The Wayback Machine - https://web.archive.org/web/20240912224217/https://www.geeksforgeeks.org/javascript-array-reduce-method/
Open In App

JavaScript Array reduce() Method

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The JavaScript Array.reduce() method iterates over an array, applying a reducer function to each element, accumulating a single output value. It takes an initial value and processes elements from left to right, reducing the array to a single result.

Syntax: 

array.reduce( function(total, currentValue, currentIndex, arr), 
initialValue )

Parameters:

This method accepts five parameters as mentioned above and described below:

  • function(total, currentValue, index, arr): It is the required parameter and is used to run for each element of the array. It contains four parameters which are listed below:
Parameter NameDescriptionRequired/Optional
totalSpecifies the initial value or previously returned value of the functionRequired
currentValueSpecifies the value of the current elementRequired
currentIndexSpecifies the array index of the current elementOptional
arrSpecifies the array object the current element belongs toOptional

initialValue: It is an optional parameter and is used to specify the value to be passed to the function as the initial value.

Return value:

The JavaScript array reduce method returns a single value/element after traversing the complete array.

Example 1: In this example, we will write a reduce function to simply print the difference of the elements of the array.

JavaScript
// Input array
let arr = [175, 50, 25];

// Callback function for reduce method
function subofArray(total, num) {
    return total - num;
}

//Function to execute reduce method 
function myGeeks(item) {

    // Display output
    console.log(arr.reduce(subofArray));
}
myGeeks()

Output
100

Example 2: This example uses reduce() method to return the sum of all array elements. 

JavaScript
// Input array
let arr = [10, 20, 30, 40, 50, 60];

// Callback function for reduce method
function sumofArray(sum, num) {
    return sum + num;
}

//Function to execute reduce method 
function myGeeks(item) {
    // Display output
    
    console.log(arr.reduce(sumofArray));
}
myGeeks();

Output
210

 Example 3: This example uses reduce() method to return the round sum of all array elements. 

JavaScript
// Input array
let arr = [1.5, 20.3, 11.1, 40.7];

// Callback function for reduce method
function sumofArray(sum, num) {
    return sum + Math.round(num);
}

//Function to execute reduce method 
function myGeeks(item) {

    // Display output
    console.log(arr.reduce(sumofArray, 0));
}
myGeeks();

Output
74

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers: The browsers supported by JavaScript Array reduce() method are listed below:

JavaScript Array reduce() method- FAQs

How does the reduce() method work with an initial value?

When provided, the initial value is used as the first argument to the first call of the reducer function. If not provided, the first element of the array is used, and the iteration starts from the second element.

Can reduce() be used to flatten an array?

Yes, reduce() can be used to flatten an array by concatenating nested arrays into a single array using the accumulator.

How can I use reduce() to sum all numbers in an array?

To sum numbers, use reduce((accumulator, current) => accumulator + current, 0), where 0 is the initial value.

Is reduce() the same as forEach()?

No, reduce() accumulates values to produce a single result, while forEach() simply iterates over array elements without returning a value.

Can reduce() be used to group array elements?

Yes, reduce() can group array elements into categories by accumulating elements into an object based on a specified condition.



Previous Article
Next Article

Similar Reads

How to use Array.prototype.reduce() method in JavaScript ?
The Array.prototype.reduce() method is used in an array to return a single value from an array after executing the user-supplied callback function on each element of the array. It transverses from the left-most-element to the right-most-element of the given array. Array.prototype.reduce() can be called using two ways. Callback function: The functio
3 min read
Implement polyfill for Array.prototype.reduce() method in JavaScript
In this article, we will learn how to implement a polyfill for an Array.prototype.reduce() method in JavaScript. A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or the new version of the browser does not have that
2 min read
How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to convert an array of objects to a map in JavaScript:
2 min read
JavaScript typedArray.reduce() Method
The typedArray.reduce() is an inbuilt function in JavaScript which is used to reduce each element of the typedArray from left to right into a single value. Syntax: typedArray.reduce(callback) Parameters: It accept a parameter callback function which accept some parameters specified below- previousValue: It is the previously returned value.currentVa
1 min read
JavaScript TypeError - Reduce of empty array with no initial value
This JavaScript exception reduce of empty array with no initial value occurs if a reduce function is used with the empty array. Message: TypeError: reduce of empty array with no initial value Error Type: TypeError Cause of Error: This error is raised if an empty array is provided to the reduce() method because no initial value can be returned in th
1 min read
Convert 2D Array to Object using Map or Reduce in JavaScript
Converting a 2D array to an object is a common task in JavaScript development. This process involves transforming an array where each element represents a key-value pair into an object where keys are derived from one dimension of the array and values from another. Problem Description:Given a 2D array where each inner array contains a key-value pair
2 min read
Difference Between array.reduce() and reduceRight() in JavaScript
The array.reduce() and array.reduceRight() are two array methods used for reducing an array to a single value. They are particularly useful for performing cumulative operations on the array elements. Although they share similar functionality, their behaviour differs in the direction they iterate through the array. This article will explain the diff
3 min read
TypeScript Array reduce() Method
The Array.reduce() method in TypeScript is used to reduce an array to a single value by applying a callback function to each element of the array. This article will provide a detailed guide on how to use the reduce() method, complete with examples to illustrate its functionality. Syntaxarray.reduce(callback[, initialValue])Parameterscallback: A fun
3 min read
Reduce a fraction to its simplest form by using JavaScript
A fraction is simplified if there are no common factors (except 1) between the numerator and the denominator. For example, 4/6 is not simplified, since 4 and 6 both share 2 as a factor. If improper fractions can be transformed into integers. There are two possible ways to simplify the fraction by using JavaScript. Using math.js simplify() FunctionU
2 min read
How to map, reduce and filter a Set element using JavaScript ?
The map(), reduce() and filter() are array functions that transform the array according to the applied function and return the updated array. They are used to write simple, short and clean codes for modifying an array instead of using the loops. map() method: It applies a given function on all the elements of the array and returns the updated array
2 min read
What is Reduce in JavaScript ?
The reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. Syntax:array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue);Parameters:callback: A functio
1 min read
How to use map(), filter(), and reduce() in JavaScript ?
The map(), filter(), and reduce() are the array functions that allow us to manipulate an array according to our own logic and return a new array after applying the modified operations on it. JavaScript map() MethodThe map() method in JavaScript is used to create a new array by applying a function to each element of the original array. It iterates t
3 min read
Collect.js reduce() Method
The reduce() method is used to reduce the collection elements into a single value according to the given callback. It works by passing the result of each iteration to the next one resulting in a single value in the end. Syntax: collect(array).reduce(callback) Parameters: The collect() method takes one argument that is converted into the collection
1 min read
Ember.js MutableArray reduce() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
Ember.js EmberArray reduce() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of web
5 min read
Ember.js ArrayProxy reduce() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of web
4 min read
Ember.js Ember.NativeArray reduce() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
Lodash _.reduce() Method
Lodash's _.reduce() method iterates over a collection, applying an iterative function to each element to accumulate a single value. The method starts with an initial value or the first element if no accumulator is provided, progressively reducing the collection. Syntax _.reduce(collection, iteratee, accumulator)Parameters: This method accepts three
2 min read
PHP | Ds\Vector reduce() Function
The Ds\Vector::reduce() function is an inbuilt function in PHP which reduce the vector to a single value by applying operations in the callback function. Syntax: mixed public Ds\Vector::reduce( $callback, $initial ) Parameters: This function accepts two parameters as mentioned above and described below: $callback: This parameter holds the function
2 min read
PHP | Ds\Deque reduce() Function
The Ds\Deque::reduce() function is an inbuilt function in PHP which is used to reduce the Deque to a single element using callback function. Syntax: public Ds\Deque::reduce( $callback, $initial ) : mixed Parameters: This function accept two parameters as mentioned above and described below: callable: It contains the operation to be performed on the
2 min read
PHP | Ds\Set reduce() Function
The Ds\Set::reduce() function is an inbuilt function in PHP which is used to reduce the set to a single value by applying operations using the callback function. Syntax: mixed public Ds\Set::reduce ( callable $callback [, mixed $initial ] ) Parameters: This function accepts two parameters as mentioned above and described below: $callback: This para
2 min read
PHP | Ds\Map reduce() Function
The Ds\Map::reduce() function is an inbuilt function in PHP which is used to reduce the map to a single value by applying operations using the callback function. Syntax: mixed public Ds\Map::reduce( $callback, $initial ) Parameter: This function accepts two parameters as mentioned above and described below: $callback: This parameter holds the funct
2 min read
PHP | Ds\Sequence reduce() Function
The Ds\Sequence::reduce() function is an inbuilt function in PHP which is used to reduce the sequence to a single value using a callback function. Syntax: mixed abstract public Ds\Sequence::reduce ( callable $callback [, mixed $initial ] ) Parameters: This function accepts two parameters as mentioned above and described below: $callback: This param
2 min read
Reduce the size of an icon during the animation
Icons and Images both are a graphical representation of the things that we want to describe but Icons have a different objective than normal Images. Icons are a general representation of an idea whereas Images are more specific. In CSS, Icons are defined using a different set of properties than normal Images. We don't use the height and width prope
3 min read
How to use motion-safe and motion-reduce in Tailwind CSS ?
Tailwind CSS is a CSS framework that helps in building rapid custom UI. It is a highly customizable, low-level CSS framework that gives you all of the building blocks that you need. In Tailwind CSS, motion-safe and motion-reduce are utility classes used for creating animations. motion-safe ensures animations play regardless of user preferences, whi
2 min read
Ways To Reduce The Loading Time Of Website | Set 1
“Patience is a virtue” – an adage that hardly holds when we consider online activities. The page load time of your website is very important. Why? It decides whether a visitor to your site will explore further, or shall part ways on the first click. Some statistical facts: A 1-second load time delay leads to 11% fewer page views, 16% decrease in cu
4 min read
Ways To Reduce The Loading Time Of Your Website | Set 2
Prerequisite: Ways To Reduce The Loading Time Of Website | Set 1 In the above article, we described four methods, namely: Optimize ImagesMinify JavaScript and Style SheetsEnable CompressionBrowser Caching In this article, we shall explore five more ways to reduce the loading time of your website. 1. Prioritize Above-the-fold Content This generally
3 min read
Underscore.js _.reduce() Function
Underscore.js _.reduce() function is an inbuilt function in Underscore.js that is used to transform an array's/object's properties into one single value or is used to create a single result from a given list of values. When all the elements of the list are passed to the function/iterate and no more elements remain then the _.each loop ends. The ite
3 min read
How to Reduce Space Between Two Columns in HTML Table ?
In HTML, we can create tables with multiple columns to display data in an organized manner. Sometimes, we may want to reduce the space between two adjacent columns in a table. We can achieve this by applying CSS properties to the table elements. In this article, we will see the different approaches to reducing the space between two columns in an HT
3 min read
How to Sort or Reduce an Object by Key in TypeScript ?
Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility. Below are the approaches used to sort or reduce an object by key in TypeScript: Table of Conte
3 min read