Enhance your JavaScript Arrays

JavaScript 1.2 added stack-like functionality to the built-in Array class in the form of four instance methods: push, pop, shift, and unshift. This wasn’t standardized in the ECMAScript spec till version 3… which apparently kept Microsoft from implementing these methods in IE 5 for Mac and Windows (although it is implemented in IE 5.5/Win)… if you need to support those browsers, you have to do a little extra work…

Due to JavaScript’s dynamism, this isn’t so hard actually… By adding methods to the Array class’ prototype object, those methods will be available to every Array object instance from then on. Looks something like this…


/**
 *   Array convenience method to add stack functionality to Arrays
 *   in browsers that do not support ECMAScript v3.
 *
 *   @param object element
 *   @returns number
 */
Array.prototype.push = function (element) {
    this[this.length] = element;
    return this.length;
};

I’ll leave pop, shift and unshift as an exercise for the reader… ;)

This technique opens up some great possibilities for arrays in other areas too… how about checking for membership?


/**
 *   Array convenience method to check for membership.
 *
 *   @param object element
 *   @returns boolean
 */
Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
};

This is like PHP’s in_array() built-in function… only elegant.

Here’s a couple more I’ve been using that were inspired by the Java Collections Framework…


/**
 *   Array convenience method to clear membership.
 *
 *   @param object element
 *   @returns void
 */
Array.prototype.clear = function () {
    this.length = 0;
};

/**
 *   Array convenience method to remove element.
 *
 *   @param object element
 *   @returns boolean
 */
Array.prototype.remove = function (element) {
	var result = false;
	var array = [];
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			result = true;
		} else {
			array.push(this[i]);
		}
	}
	this.clear();
	for (var i = 0; i < array.length; i++) {
		this.push(array[i]);
	}
	array = null;
	return result;
};

Any other ideas?

Leave a Reply