Given an array [1, 2, 3, 4]
, how can I find the sum of its elements? (In this case, the sum would be 10
.)
I thought $.each might be useful,
If you happen to be using Lodash you can use the sum function
array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10
var arr = [1,2,3,4];
var total=0;
for(var i in arr) { total += arr[i]; }
When the array consists of strings one has to alter the code. This can be the case, if the array is a result from a databank request. This code works:
alert(
["1", "2", "3", "4"].reduce((a, b) => Number(a) + Number(b), 0)
);
Here, ["1", "2", "3", "4"] ist the string array and the function Number()
converts the strings to numbers.
I am a beginner with JavaScript and coding in general, but I found that a simple and easy way to sum the numbers in an array is like this:
var myNumbers = [1,2,3,4,5]
var total = 0;
for(var i = 0; i < myNumbers.length; i++){
total += myNumbers[i];
}
Basically, I wanted to contribute this because I didn't see many solutions that don't use built-in functions, and this method is easy to write and understand.
arr.reduce(function (a, b) {
return a + b;
});
Reference: Array.prototype.reduce()
Use a for
loop:
const array = [1, 2, 3, 4];
let result = 0;
for (let i = 0; i < array.length - 1; i++) {
result += array[i];
}
console.log(result); // Should give 10
Or even a forEach
loop:
const array = [1, 2, 3, 4];
let result = 0;
array.forEach(number => {
result += number;
})
console.log(result); // Should give 10
For simplicity, use reduce
:
const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);
console.log(result); // Should give 100