Additional methods for JavaScript Array

Below is a basic set of additions to the JavaScript Array prototype to make it easier to work with numeric arrays.

Disclaimer: these additions work for me, but I can’t vouch for their correctness or efficiency, with all values in all situations on all platforms.

I’m also aware that adding methods to an existing class is, in many situations, a bad idea! These additions were useful to me in a highly constrained context but, obviously, this kind of approach does not scale well, particularly with multiple coders and multiple JavaScript libraries.


Array.prototype.absMax = function(){
return Math.max.apply({}, Math.abs(this));
};

Array.prototype.absMin = function(){
return Math.min.apply({}, Math.abs(this));
};

Array.prototype.avg = function(){
return this.sum() / this.length;
};

Array.prototype.max = function(){
return Math.max.apply({}, this);
};

Array.prototype.median = function(){
var sortedArray = this.slice().sort(function(a, b){return a - b;}); // make a deep copy and sort it
return sortedArray[Math.floor(this.length / 2)]; // for one item, i = 0; two items, i = 1; 3 items, i = 1...
};

Array.prototype.min = function(){
return Math.min.apply({}, this);
};

Array.prototype.numSort = function(){
return this.sort(function(a, b){return a - b;});
};

Array.prototype.sum = function(){
for (var i = 0, sum = 0 ; i != this.length; ++i) {
var n = this[i];
if(!isNaN(n)) {
sum += n;
}
}
return sum;
};

Advertisements

About Sam Dutton

I am a Developer Advocate for Google Chrome. I grew up in rural South Australia, went to university in Sydney, and have lived since 1986 in London, England. Twitter: @SW12
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s