The Array.reduce()
method is a powerful JavaScript function that processes each element of an array to reduce it to a single output value. It iterates through the array while accumulating a result based on the logic provided in a callback function.
Syntax
arr.reduce(callback(accumulator, currentValue, index, array), initialValue);
Parameters
Parameter | Description |
---|---|
callback | (Required) A function that executes on each element of the array. |
accumulator | (Required in callback ) The accumulated result from previous callback executions. |
currentValue | (Required in callback ) The current element being processed. |
index | (Optional in callback ) The index of the current element. |
array | (Optional in callback ) The array reduce() is being applied on. |
initialValue | (Optional) A value to use as the initial accumulator . If not provided, the first element of the array is used. |
Return Value
The reduce()
method returns the final accumulated value after iterating through all elements of the array.
Example 1: Summing Array Elements
let arr = [10, 20, 30, 40, 50]; let sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // Output: 150
Example 2: Multiplying Array Elements
let arr = [1, 2, 3, 4]; let product = arr.reduce((accumulator, currentValue) => accumulator * currentValue, 1); console.log(product); // Output: 24
Example 3: Flattening an Array
let arr = [[1, 2], [3, 4], [5, 6]]; let flatArray = arr.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6]
Example 4: Counting Occurrences
let arr = ['apple', 'banana', 'apple', 'cherry', 'banana', 'banana']; let count = arr.reduce((accumulator, fruit) => { accumulator[fruit] = (accumulator[fruit] || 0) + 1; return accumulator; }, {}); console.log(count); // Output: { apple: 2, banana: 3, cherry: 1 }
Example 5: Finding the Maximum Value
let arr = [10, 25, 5, 30, 15]; let max = arr.reduce((accumulator, currentValue) => currentValue > accumulator ? currentValue : accumulator ); console.log(max); // Output: 30
Supported Browsers
Browser | Support |
---|---|
Chrome | 3+ |
Firefox | 3+ |
Safari | 4+ |
Edge | 12+ |
Opera | 10.5+ |
Internet Explorer | 9+ |