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 few people have suggested adding a .sum()
method to the Array.prototype
. This is generally considered bad practice so I'm not suggesting that you do it.
If you still insist on doing it then this is a succinct way of writing it:
Array.prototype.sum = function() {return [].reduce.call(this, (a,i) => a+i, 0);}
then: [1,2].sum(); // 3
Note that the function added to the prototype is using a mixture of ES5 and ES6 function and arrow syntax. The function
is declared to allow the method to get the this
context from the Array
that you're operating on. I used the =>
for brevity inside the reduce
call.