The reduce() method iterates through each array element, applying a function to accumulate them into a single value.
It operates from left to right within the array. For its counterpart, see reduceRight().
The reduce() method does not alter the original array. |
This example demonstrates finding the sum of all numbers within an array:
Example
const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction); function myFunction(total, value, index, array) { return total + value; } |
It’s worth noting that the callback function accepts four arguments:
In the provided example, since the index and array parameters are not utilized, they can be omitted:
Example
const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction); function myFunction(total, value) { return total + value; } |
The reduce() method can optionally take an initial value.
Example
const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction, 100); function myFunction(total, value) { return total + value; } |
The reduceRight() method iterates through each array element, applying a function to accumulate them into a single value.
It operates from right to left within the array. For its counterpart, see reduce().
The reduceRight() method does not alter the original array. |
This example demonstrates finding the sum of all numbers within an array:
Example
const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduceRight(myFunction); function myFunction(total, value, index, array) { return total + value; } |
Keep in mind that the function accepts four arguments:
In the example provided, the index and array parameters are not utilized. Thus, it can be simplified as:
Example
const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduceRight(myFunction); function myFunction(total, value) { return total + value; } |