reduce()
is a higher-order function for arrays in JavaScript, used to aggregate all elements of an array into a single value in some way. Its basic usage involves providing a callback function that receives four parameters: accumulator
, currentValue
, currentIndex
, and array
. The accumulator
is used to store the result of each iteration, while currentValue
is the value of the current iteration item.
Syntax:#
array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
callback
: The callback function to execute, receiving four parameters:accumulator
: The value returned from the last invocation of the callback function, or the initial value (initialValue
).currentValue
: The current element being processed in the array.index
: The index of the current element (starting from 0).array
: The original array being operated on.
initialValue
(optional): Specifies the initial value ofaccumulator
when the callback function is first called. If noinitialValue
is provided, the default initial value ofaccumulator
is the first element of the array, andcurrentValue
starts from the second element of the array.
Example 1: Sum of Array Elements#
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); // 0 is the initial value
console.log(sum); // 15
Example 2: Array Deduplication#
const numbers = [1, 2, 3, 4, 3, 2, 1];
const uniqueNumbers = numbers.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueNumbers); // [1, 2, 3, 4]
Example 3: Count Occurrences of Each Element in an Array#
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];
const fruitCount = fruits.reduce((accumulator, currentValue) => {
if (accumulator[currentValue]) {
accumulator[currentValue] += 1;
} else {
accumulator[currentValue] = 1;
}
return accumulator;
}, {});
console.log(fruitCount); // { apple: 2, banana: 3, orange: 1 }
Example 4: Chained Operations#
const numbers = [1, 2, 3, 4];
const result = numbers
.reduce((acc, currentValue) => acc + currentValue, 0)
.toString()
.split('')
.reverse()
.join('');
console.log(result); // "10" (the number 10 is reversed to "01")
Summary#
reduce()
is a very powerful method suitable for various scenarios such as array aggregation, transformation, counting, etc. It can simplify complex operations into a single line of code, but beginners may find it a bit abstract.