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

  • 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

  • Hi – this whole prototype stuff is new to me. How do I call this method/function from the code?

    RecycledBottle

    April 13, 2009, 11:52 am

  • The recursive sum implementation is likely to run into the recursion limit, so you won’t be able to sum arrays of more than about 1000 items, which is an unreasonably low limit. The iterative implementation should be preferred. There’s also no advantage to avoiding those variable declarations.

    Christian Oudard

    April 28, 2009, 1:17 pm

  • For array length > 1e5 the recursive version of sum will start eating a *lot* of stack space.
    This version finishes under 0.5 seconds (IE 8) for an array of milion integers.

    Array.prototype.sum = function() {
    for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]);
    return sum;
    }

    Also, if anyone wants to sum anything other than numbers, I will not stop them …

    –DBJ

    DBJ

    November 20, 2009, 7:32 am

Sorry, this discussion is closed.