In JavaScript, reduce is a powerful array method that processes each element in an array one by one and combines them into a single value. It can be used in various scenarios, from calculating sums to transforming data, making it very useful.
Basic Syntax
The basic syntax of the reduce method is as follows:
|
|
Here, array is the array to be operated on, callback is a callback function for processing each array element, and initialValue is an optional initial value. The specific parameter descriptions are as follows:
function(total, currentValue, currentIndex, arr)
— Required. The function to execute for each array element.total
— Required. The initial value, or the return value after computation.currentValue
— Required. The current element.currentIndex
— Optional. The index of the current element.arr
— Optional. The array object to which the current element belongs.
initialValue
— Optional. The initial value passed to the function.
Process
Use
total
as the initial value of the accumulated result. If totalis not set, the first element of the array is used as theinitialValue
.Start iterating, process
currentValue
with the accumulator, accumulate the mapping result ofcurrentValue
ontototal
, end this loop, and returntotal
.Enter the next loop, repeat the above operation, until the last element of the array.
End the iteration and return the final
total
.
Usage Examples
- Calculating the Sum of an Array
|
|
- Transforming Array Elements
|
|
- Finding the Maximum Value
|
|
Advanced Usage
Flatten Array
|
|
Split Array
|
|
Counting Occurrences
|
|
Tracking Positions
|
|
Combination Function
|
|
Array Deduplication
|
|
Calculate the Average Value
|
|
Array Max and Min Values
|
|
URL Parameter Deserialization
|
|
URL Parameter Serialization
|
|
Grouping Objects
|
|
Create Lookup Map
Use reduce()
to create a lookup map from an array. After mapping, the time complexity becomes O(1).
|
|
Merge Multiple Arrays into One Object
|
|
Check if a String is a Palindrome
|
|