spudly.shuoink.com

the best way to predict the future is to implement it

Entries Comments


Array.min() && Array.max() && Array.sum()

1 June, 2008 (19:38) | General

Here’s three array methods that might be useful: min(), max(), and sum(). I’m sure you can guess what they do, but I’m going to tell you anyway. Note that for all three functions, the entire array must have only numeric values.

First, we have min(). This finds the smallest number in the array and returns it.

Usage:

var list = [ 1, 2, 3, 4, 5, 6, 7 ];
var min = list.min(); // min is now 1
Array.prototype.min = function() {

   if ( this.length == 0 || typeof this[0] != "number" ) {
      return null; // TODO: how about we throw an error instead, eh?
   }

   var min = this[0];
   for ( var i = 1; i < this.length; i++ ) {
      if ( typeof this[i] != "number" ) {
         return null; // TODO: how about we throw an error instead, eh?
      }
      if ( this[i] < min ) {
         min = this[i];
      }
   }
   return min;
};

Next, we have max(). This finds the largest number in the array and returns it.

Usage:

var list = [ 1, 2, 3, 4, 5, 6, 7 ];
var max = list.max(); // max is now 7
Array.prototype.max = function() {

   if ( this.length == 0 || typeof this[0] != "number" ) {
      return null; // TODO: how about we throw an error instead, eh?
   }

   var max = this[0];
   for ( var i = 1; i < this.length; i++ ) {
      if ( typeof this[i] != "number" ) {
         return null; // TODO: how about we throw an error instead, eh?
      }
      if ( this[i] > max ) {
         max = this[i];
      }
   }
   return max;
};

Lastly, sum() calculates the sum of all the values in the array.

Usage:

var list = [ 1, 2, 3, 4, 5, 6, 7 ];
var sum = list.sum(); // sum is now 28
Array.prototype.sum = function() {

   if ( this.length == 0 ) {
      return;
   }

   var sum = 0;
   for ( var i = 0; i < this.length; i++ ) {
      if ( typeof this[i] != "number" ) {
         return;
      }
      sum += this[i];
   }
   return sum;

};

« Array.difference();

 Array.each(); »

Comments

Comment from mark evans
Time: June 2, 2008, 7:32 pm

kudos on a slick site (xclnt typography/design).

btw- for arrays you can always use native math min/max — e.g Array.prototype.min= function(){ return Math.min.apply(null,this)}; there is no explicit error checking but Math.min/max/etc do return NaN if given non-numeric values in the arguments.

Comment from spudly
Time: June 3, 2008, 6:24 am

Mark - thanks for the suggestion. I’ll be using that in the future.

Write a comment