JavaScript reduce() method
The reduce()
method in JavaScript is a powerful array method used to execute a provided callback function on each element of the array (from left to right) to reduce it to a single value. It is commonly used for accumulating or combining values.
Syntax:
callback
: A function that is called for each element in the array. It can accept up to four parameters:accumulator
: The accumulated value previously returned in the last invocation of the callback, orinitialValue
, if supplied.currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The arrayreduce()
was called upon.
initialValue
(optional): A value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used, andreduce()
will start from the second element.
Return Value:
- The final, single value that results from the reduction process. If the array is empty and no initial value is provided, a
TypeError
will be thrown.
Key Points:
- Accumulates values: The
reduce()
method is typically used to accumulate values, such as summing numbers or combining arrays. - Can return any type: The result can be a number, string, object, array, etc., depending on the logic implemented in the callback.
- Modifies the initial value: If an
initialValue
is provided, it will be used as the first accumulator; otherwise, the first element in the array will be used.
Example 1: Basic usage (Sum of numbers)
Example 2: Using arrow function (Product of numbers)
Example 3: Flattening an array
Example 4: Counting occurrences of values
Example 5: Using thisArg
Summary:
- The
reduce()
method is a versatile and powerful way to accumulate or combine values from an array into a single output. - It can be used for various purposes, including summing, multiplying, flattening arrays, or counting occurrences of values.
- The method provides flexibility in defining how the accumulation occurs through the
callback
function and allows for initialization with aninitialValue
.