Reducing an Array
Reducing an Array: reduce()
The reduce()
method is a powerful array method in JavaScript used to reduce an array into a single value. It iterates over each element of the array and applies a callback function to accumulate a result.
The reduce()
function takes two main arguments: the callback function and an (optional) initial value.
The callback function is called for each element in the array and is responsible for accumulating the result. The result is then carried over to the next iteration. The final result is returned after iterating through all the array elements.
-
callbackFn
: A function that is called for each element in the array. It takes four arguments:accumulator
: The accumulated result from previous iterations or the initial value.currentValue
: The current element being processed in the array.currentIndex
: (Optional) The index of the current element being processed.array
: (Optional) The array reduce() was called upon.
-
initialValue
: (Optional) The initial value for the accumulator. If not provided, the first element of the array is used as the initial value.
Examples
Example 1, letβs use the reduce()
to find the sum of all elements in an array:
Example 2, counting the number of occurrences of elements in an array using reduce()
: