Search code examples
javascriptprototype-programming

Javascript - creating a new Array method


I would like to extend the Javascript built-in Array object by addind a new method: searchByRegexp

Basically the method will get a regexp as input and will return:
_ a string representing the element of the array that matches the regexp (if more than one match, the first one will be returned)
_ an empty string if none of the elements matches the regular expression.


Solution

  • Quick and dirty (fiddle for your fiddling pleasure):

    Array.prototype.searchByRegexp = function (rx) {
        for(var i = 0, ln = this.length; i < ln; i++) {
            // test item i
            if(rx.test(this[i])) {
                return this[i] + "";
            }
        }
        // return an empty string if no matches are found
        return "";
    }
    

    However, you may wish to implement more general methods instead...

    Array.prototype.find = function(delegate) {   
        for(var i = 0, ln = this.length; i < ln; i++) {
            if(delegate(this[i])){
                return this[i];   
            }
        }
        return null;
    }
    
    Array.prototype.findAll = function(delegate) {   
        var results = [];
        for(var i = 0, ln = this.length; i < ln; i++) {
            if(delegate(this[i])){
                results.push(this[i]);   
            }
        }
        return results ;
    }
    
    Array.prototype.each = function (delegate) {
        for (var i = 0, ln = this.length; i < ln; i++) {
            delegate(this[i], i);
        }
    }
    

    ... which could then perform regex comparison like so:

    // test values
    var sizes = ["Small", "Medium", "Large", "Extra-Large", "Extra-Extra-Large"];
    
    // Print single value or blank
    document.write(sizes.find(function(size){
        return /large/i.test(size);
    }) || "");     
    
    // horizontal rule to separate our results
    document.write("<hr/>");
    
    // Print all matches
    sizes.findAll(function(size){
        return /large/i.test(size);
    }).each(function(size){
        document.write(size + "<br/>"); 
    });