What is JavaScript Array reduce() Method?
Introduction -
In this article, we will talk about the javascript reduce method. At the end of this article, we will gain valuable insight into where to use the reduce method.
To better understand the reduce method you can use the online javascript editors to execute the examples. For example -
1. https://onecompiler.com/javascript
2. https://jsfiddle.net/
Reduce Operation -
Before diving into what is the use of the reduce() method. let's find distinguish what problem it tries to solve: reducing an array to a value.
Reducing an array means performing a concrete accumulative operation on its items to calculate a result value.
A good example of reduce operation is calculating the sum of an array, where the accumulative operation is the addition of items.
For an array [5, 2, 9, 4] reducing to a sum results in 20.
Reduce Method -
This is an array method that operators on the array.
Used to reduce the array to a single value and executes a provided function for each value
of the array and return value of the function is stored in an accumulator.
The array.reduce() is a method on array that accepts 2 arguments:
Syntax-
array.reduce(callbackFn[, initialValue]);
The callback function is an obligatory argument that is a function performing the reduce operation,
and the second optional argument is the initial value.
JavaScript invokes the callback function upon each item of the array with 4 arguments:
1. the accumulator value,
2. the current array item,
3. the current array item index, and
4. the array itself.
The callback function must return the updated accumulator value.
Callback function Syntax-
array.reduce(function(accumulator, item, index, array) {
// Use `accumulator` and `item`
// to calculate `updatedAccumulator`...
return updatedAccumulator;
})
Conclusion -
reduce() is a useful method that reduces an array to a value.
Would you like to read more about reduce method?
Visit the javascript documentation by mozilla.
Helpful excellent
ReplyDelete