How to use Array.prototype.reduce() method In Javascript
The reduce() method provides a functional programming approach to summing array elements. This method takes a reducer function that accumulates the sum of the array elements and an initial value for the accumulator.
Example: To illustrate the use of `reduce()` method to compute the sum of all elements in an array and then prints the result.
let array = [1, 2, 3, 4, 5];
let sum = array.reduce((accumulator,
currentValue) => accumulator + currentValue, 0);
console.log(sum);
Output
15
How to Add the Numbers in a JavaScript Array?
Adding the numbers in a JavaScript array is a common operation, particularly in tasks involving data aggregation or mathematical calculations. This process involves iterating through the array and summing its elements. JavaScript provides multiple methods to achieve this, ranging from traditional loops to more modern and concise array methods.
Table of Content
- Using a For Loop
- Using a While Loop
- Using Array.prototype.reduce()
- Using For-Of Loop