Array.reduce()
The Array.reduce()
method in JavaScript executes a callback function on each element of the array, resulting in a single output value. It’s often used for operations like summing values, flattening arrays, or building more complex transformations.
Syntax
array.reduce(callbackFn)
array.reduce(callbackFn, initialValue)
Parameters
Parameter | Description |
---|---|
callbackFn | A function to execute on each element in the array, taking four arguments: accumulator (the accumulated result), currentValue (the current element being processed), currentIndex (the index of the current element), and array (the array reduce was called on). |
initialValue | An optional value to use as the first argument to the first call of the callback. If no initialValue is provided, the first element in the array is used as the initial accumulator value. |
Return Value
The reduce()
method returns the value that results from the reduction process. If the array is empty and no initialValue
is provided, a TypeError
is thrown.
Examples
1. Summing Array Elements
Using reduce()
to calculate the sum of an array’s elements.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);
Output
10
- The
accumulator
starts at0
(theinitialValue
). - Each element of the array is added to the
accumulator
, resulting in the sum of10
.
2. Flattening an Array
Using reduce()
to flatten a nested array into a single-level array.
const nestedArray = [[1, 2], [3, 4], [5]];
const flattened = nestedArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flattened);
Output
[1, 2, 3, 4, 5]
In this example, concat()
is used to merge each sub-array into the accumulator
.
3. Counting Instances of Values
Using reduce()
to count the frequency of elements in an array.
const items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const count = items.reduce((accumulator, item) => {
accumulator[item] = (accumulator[item] || 0) + 1;
return accumulator;
}, {});
console.log(count);
Output
{ apple: 3, banana: 2, orange: 1 }
This example uses reduce()
to build an object where the keys are array elements and the values are their counts.
4. Calculating Maximum Value
Using reduce()
to find the largest number in an array.
const numbers = [10, 25, 8, 50, 12];
const max = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue), -Infinity);
console.log(max);
Output
50
The callback compares the accumulator
with the currentValue
to track the largest number.
5. Using reduce()
Without an Initial Value
When no initialValue
is provided, the first element of the array is used as the initial accumulator.
const numbers = [5, 10, 15];
const result = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(result);
Output
30
Here, 5
(the first element) is used as the starting accumulator
value.