How to use reduce() array method in javascript
Table of contents
Array methods were introduced in javascript in ES5. Before this, every array iteration was performed by loops. But after the introduction of array methods to perform array operations, work on an array has become very easy without the implementation of extra coding.
Here we will discuss some array methods.
why use reduce()?
It reduces all elements of the array in a single value of accumulation like the sum of all elements. This method is iterative. It runs a callback function to reduce all elements. This method is not valid for empty arrays. It does not get changed original array.
Syntax
array.reduce(callbackfunction (accumulator, currentvalue, currentindex, array), initialvalue)
Parameters
callbackfunction
A function that gives code to reduce array elements. It returns the value of the accumulator.
The function passes the following arguments-
accumulator
It contains the initial value and return value of the callback function. If initialvalue is not specified, it takes the value of array[0].
currentvalue
It contains the value of current element. If initialvalue is not mentioned, it takes the value of the array[1] on the first call.
currentindex(optinal)
It contains an index of the current element. If initialvalue is not specified it takes 1 otherwise 0.
array(optional)
It is an array on which an operation is being performed.
initialvalue
On the first call, it gives value to accumulation. If initialvalue is not specified, then callbackfunction operates on the second value of an array otherwise the first value of an array.
Example
Sum up all array elements to reduce in a single value.
Output: