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,
A short piece of JavaScript code would do this job:
var numbers = [1,2,3,4];
var totalAmount = 0;
for (var x = 0; x < numbers.length; x++) {
totalAmount += numbers[x];
}
console.log(totalAmount); //10 (1+2+3+4)
Here's an elegant one-liner solution that uses stack algorithm, though one may take some time to understand the beauty of this implementation.
const getSum = arr => (arr.length === 1) ? arr[0] : arr.pop() + getSum(arr);
getSum([1, 2, 3, 4, 5]) //15
Basically, the function accepts an array and checks whether the array contains exactly one item. If false, it pop the last item out of the stack and return the updated array.
The beauty of this snippet is that the function includes arr[0]
checking to prevent infinite looping. Once it reaches the last item, it returns the entire sum.
i saw all answers going for 'reduce' solution
var array = [1,2,3,4]
var total = 0
for (var i = 0; i < array.length; i++) {
total += array[i]
}
console.log(total)
Funny approach:
eval([1,2,3].join("+"))
You can combine reduce() method with lambda expression:
[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);
Anyone looking for a functional oneliner like me? Take this:
sum= arr.reduce(function (a, b) {return a + b;}, 0);