The reduce() method reduces the given array into a single value by executing a reducer function. The user implements the reducer function that works on every element present in the array.
The reducer function is the user implemented code. It uses the following four arguments to perform its task:
callback: The main is the callback function that executes for each element, excluding the first, if no initialValue is specified.
The callback function undertakes the following four arguments:
initialValue: It is the first argument value used in the first invocation of the callback function.
It returns a single value as an output.
Points to note:
Thus, it is safe and good to provide the initial value.
Let's implement some examples to understand better:
Here's a simple example to sum up the array elements and display the output.Test it Now
Here's an example to display the difference of the array elements using reduce() method.Test it Now
Here's an example to total the array elements using the arrow function.Test it Now
When the array contain a single value only.Test it Now
Thus, in presence of a single array element, there is no need to create a callback function. Also, because when an array contain a single element, the callback is not invoked.
We can perform several examples using the array reduce() method.