In JavaScript, the sum of an array can be calculated using a variety of methods. In this tutorial, we will explore different ways to find the sum of an array using different JavaScript functions and techniques.
- Using a For Loop:
One of the simplest ways to find the sum of an array in JavaScript is by using a for loop. You can iterate through each element of the array and add them up to get the sum. Here’s an example:
const arr = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log(sum); // Output: 15
- Using the Array.reduce() Method:
The reduce() method in JavaScript can be used to reduce an array to a single value. In this case, we can use it to find the sum of an array. Here’s an example:
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15
- Using the Array.forEach() Method:
Another way to find the sum of an array in JavaScript is by using the forEach() method. This method iterates over each element of the array and performs a specified action on each element. Here’s an example:
const arr = [1, 2, 3, 4, 5];
let sum = 0;
arr.forEach((num) => {
sum += num;
});
console.log(sum); // Output: 15
- Using a While Loop:
You can also find the sum of an array using a while loop. This involves creating a variable to keep track of the index of the array and iterating through until you reach the end of the array. Here’s an example:
const arr = [1, 2, 3, 4, 5];
let sum = 0;
let i = 0;
while (i < arr.length) {
sum += arr[i];
i++;
}
console.log(sum); // Output: 15
- Using the ES6 Spread Operator:
You can also find the sum of an array using the ES6 spread operator. This involves spreading the elements of the array into individual arguments of the reduce() method. Here’s an example:
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15
In conclusion, there are several ways to find the sum of an array in JavaScript. You can choose the method that best suits your coding style and preference. Hopefully, this tutorial has provided you with a better understanding of how to calculate the sum of an array in JavaScript.
If i use lodash?)
Yehhhh, I'm a MIDDLE !
i'm senior engineer from india, please rate my solution: import * as fs from 'fs';
import * as http from 'http';
class Calculator {
constructor(public data: number[]) {}
async getSum(): Promise<number> {
return new Promise((resolve) => {
setTimeout(() => {
let total = 0;
for (let i = 0; i < this.data.length; i++) {
new Promise<number>((res) => {
setTimeout(() => {
res(this.data[i]);
}, 1000);
}).then((num) => {
for (let j = 0; j < num; j++) {
total++;
}
if (i === this.data.length – 1) {
resolve(total);
}
});
}
}, 2000);
});
}
}
const arr = [1, 2, 3, 4];
const obj = new Calculator(arr);
obj.getSum().then((total) => {
console.log(`The sum is: ${total}`);
});
Words are correct but the examples are wrong
I'm only a junior 😢😢😢😢