JavaScript reduce() Method
The reduce()
method in JavaScript is used to reduce an array to a single value. It executes a provided callback function once for each element in the array, resulting in a single output value. The callback function takes four arguments: accumulator, currentValue, currentIndex, and the array itself.
Syntax:
arr.reduce(function(){
...
})
Example: Using JavaScript’s reduce() Method to Accumulate Array Elements
The code initializes an array arr
with values [2, 4, 8, 10]. The reduce()
method is then used to accumulate the elements of arr
by adding them together. However, the code has a mistake where curr
is mistakenly assigned prev + curr
instead of adding prev
and curr
. Additionally, the initial value for the accumulator is not provided. Thus, the code will result in an error.
let arr= [2,4,8,10]
let updatedArr = arr.reduce((prev, curr)=> curr= prev+curr)
console.log(arr);
console.log(updatedArr);
Output
[ 2, 4, 8, 10 ] 24
The table below shows the comparison of properties of the above-mentioned methods:
Property | map() | filter() | reduce() |
---|---|---|---|
Return type | Returns a new array | Returns a new array | Returns a single element |
Action | Modifies each element of the array | Filter out the element which passes the condition | Reduces array to a single value |
Parameters | value, index, array | value, index, array | accumulator, value, index, array |
Contact Us