This article shows multiple ways to return the sum for an array of numbers in Javascript.
let’s declare an array as input
var myarray = [7, 8, 1, 9];
Output:
7+8+1+9=25
You can check related posts.
Sum of an array of numbers in javascript
- use for index loop
for index, the loop is a basic loop in Any programming language.
It iterates an array using an index starting from zero until the length of the array is reached.
A temporary variable is created to sum each iterate array value and store it.
Here is an example code
var myarray = [7, 8, 1, 9];
var result = 0;
for (var i = 0; i < myarray.length; i++) {
result += myarray[i];
}
console.log(result); //25
- use the for-of loop ES6 provides a for-of loop to iterate an array of elements in another way.
Syntax:
for(index of array){
get element using array[i] syntax
}
Here is an example
var myarray = [7, 8, 1, 9];
var sum = 0;
for (var k in myarray) {
sum += myarray[k];
}
console.log(sum)
Output:
25
- use a forEach loop
Another way to iterate an array in javascript using the forEach
loop.
forEach
loop accepts callback with each element.
Callback can be normal function or arrow functions in ES6.
Here is an example.
let result=0;
myarra.forEach(item => {
result+=item;
});
console.log(result) // 25
- use lodash sum function
if you are using lodash in your project, It provides the sum() function that returns the addition of numbers in an array.
Here is an lodash sum function example.
var myarray = [7, 8, 1, 9];
result = _.sum(myarray);
console.log(result)// 25
- use array reduce function
Array provides reduce function and reduces the array elements.
It accepts a callback function.
Written call back function with arrow syntax in ES6 to the sum of the numbers.
Here is an example code
var myarray = [7, 8, 1, 9];
const sum = (first, second) => first + second
const result= myarray.reduce(sum);
console.log(result)// 25
Conclusion
As a result, Shown multiple ways to the addition of numbers in an array.