sum() Array prototype for JavaScript
Recently, I needed to sum the numbered values in my JavaScript array. Unfortunately, sum is not a native method for the Array object. So if we want to add sum to all instances of our arrays, we can assign the sum() function to Array.prototype:
Array.prototype.sum = function() {
return (! this.length) ? 0 : this.slice(1).sum() +
((typeof this[0] == 'number') ? this[0] : 0);
};
Since we’re operating over the length of the array, we can simply shift (or slice) the first element from the array and continue summing the remaining portion of the array (from element 1 - n). Once we’ve sliced the last element from the array, it will have a length of zero and will pass the logic check (! this.length).
((typeof this[0] == ‘number’) ? this[0] : 0) ensures that the value at position [0] is indeed a number. If it isn’t, we simply add 0 instead.
Examples:
[1,2,3,4,5].sum() //--> returns 15
[1,2,'',3,''].sum() //--> returns 6
[].sum() //--> returns 0
Optionally, the body of sum() can be written non-recursively:
var s = 0;
for (var i = 0; i < this.length; i++) {
s += (typeof this[i] == 'number') ? this[i] : 0;
}
return s;
The above code creates two extra variables, s and i, during execution to store the summation and the loop index. The recursive version of sum() avoids these variable declarations.
Discussion
Leave a comment...
Great function dude, works really well.
thanks heaps.
Tan
April 17, 2008, 7:08 pm
Good work. Couldn’t you do it like this?
Array.prototype.sum = function() {
return (! this.length) ? 0 : this.slice(1).sum() +
(parseFloat(this[0]));
};
Use the parseFloat() function to make it a little more versatile.
Trevor
April 30, 2008, 11:26 am
Leave a comment