Here are the 5 ways to find the sum of an array of numbers in JavaScript:
- Using array.reduce() method
- Using the array.forEach() method
- Using the array.map() method
- Using for loop
- Using while loop
Method 1: Using array.reduce() method
The easiest way to find a sum of an array is to use the array.reduce() method. It can iterate through an array, and adding the current element value to the sum of the previous element values reduces an array to a single value.
Visual Representation
Example
let data = [11, 21, 46, 19, 18];
sum = data.reduce((a, b) => {
return a + b;
});
console.log('The sum is: ', sum);
Output
The sum is: 115
Method 2: Using the array.forEach() method
You can get the sum of the elements of a JavaScript array using a forEach() method.
Example
let data = [11, 21, 46, 19, 18];
let sum = 0
data.forEach(element => {
sum += element;
});
console.log(sum);
Output
115
Method 3: Using the array.map() method
You can use the array.map() method to get the sum of the numbers of an array.
Example
let data = [11, 21, 46, 19, 18];
let sum = 0
data.map(x => sum += x);
console.log(sum);
Output
115
Method 4: Using for loop
let data = [11, 21, 46, 19, 18];
let sum = 0
for (let i = 0; i < data.length; i++) {
sum += data[i];
}
console.log(sum);
Output
115
Method 5: Using a while loop
let data = [11, 21, 46, 19, 18];
let sum = 0
let i = -1
while (++i < data.length) {
sum += data[i];
}
console.log(sum);
Output
115