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,
Those are really great answers, but just in case if the numbers are in sequence like in the question ( 1,2,3,4) you can easily do that by applying the formula (n*(n+1))/2 where n is the last number
This is much easier
function sumArray(arr) {
var total = 0;
arr.forEach(function(element){
total += element;
})
return total;
}
var sum = sumArray([1,2,3,4])
console.log(sum)
You can also use reduceRight.
[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})
which results output as 21.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight
var totally = eval(arr.join('+'))
That way you can put all kinds of exotic things in the array.
var arr = ['(1/3)','Date.now()','foo','bar()',1,2,3,4]
I'm only half joking.
No need to initial value
! Because if no initial value
is passed, the callback function
is not invoked on the first element of the list, and the first element is instead passed as the initial value
. Very cOOl feature :)
[1, 2, 3, 4].reduce((a, x) => a + x) // 10
[1, 2, 3, 4].reduce((a, x) => a * x) // 24
[1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4
[1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1
Object.defineProperty(Object.prototype, 'sum', {
enumerable:false,
value:function() {
var t=0;for(var i in this)
if (!isNaN(this[i]))
t+=this[i];
return t;
}
});
[20,25,27.1].sum() // 72.1
[10,"forty-two",23].sum() // 33
[Math.PI,0,-1,1].sum() // 3.141592653589793
[Math.PI,Math.E,-1000000000].sum() // -999999994.1401255
o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
console.log(o.sum()); // 53.519999999999996