Javascript Array.indexOf() and Array.remove()

Useful convenience methods for array manipulation in Javascript.

Array.indexOf()

Find index of given element in array. This method is implemented in some browsers, but not all.

if (!Array.prototype.indexOf)
{
    /**
     * Add array.indexOf() functionality (exists in >FF 1.5 but not in IE)
     *
     * @param {Object} elem Element to find.
     * @param {Number} [from] Position in array to look from.
     */    
    Array.prototype.indexOf = function(elem /*, from*/) {
        var len = this.length;
        
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0) {
            from += len;
        }
        
        for (; from < len; from++) {
            if (from in this && this&#91;from&#93; === elem) {
                return from;
            }
        }
        
        return -1;
    };
}
&#91;/sourcecode&#93;

<h3>Array.remove()</h3>
Remove element in array (depends on indexOf method).


if (!Array.prototype.remove)
{
    /**
     * Add array.remove() convenience method to remove element from array.
     * 
     * @param {Object} elem Element to remove.
     */
    Array.prototype.remove = function(elem) {
        var index = this.indexOf(elem);
        
        if (index !== -1) {
            this.splice(index, 1);
        }        
    };
}

Simply add these two your Javascript file augment the functionality with the existing Array implementation.