Regular Expression in Array.indexOf()

A few minutes ago I found I needed to find the first index of an element in an array using RegEx. Unfortunately, such a tool is not in the JavaScript toolbox so without further delay, here’s what I came up with.

http://jsfiddle.net/CreativeNotice/66KKr/

/**
 * Regular Expresion IndexOf for Arrays
 * This little addition to the Array prototype will iterate over array
 * and return the index of the first element which matches the provided
 * regular expresion.
 * Note: This will not match on objects.
 * @param  {RegEx}   rx The regular expression to test with. E.g. /-ba/gim
 * @return {Numeric} -1 means not found
 */
if (typeof Array.prototype.reIndexOf === 'undefined') {
    Array.prototype.reIndexOf = function (rx) {
        for (var i in this) {
            if (this[i].toString().match(rx)) {
                return i;
            }
        }
        return -1;
    };
}

// Try it out

// Array of strings
// Should return 3
var test = ['foo', '-bar', 'droopy', 'dog'];
console.log( 'array of strings:', test.reIndexOf(/og/) );

// Array with numbers
// Should return 3
var test = ['foo', '-bar', '1', 2];
console.log( 'array with numbers:', test.reIndexOf(/2/) );

// Array with objects
// Should return 3
var test = ['foo', { 'test':'one' }, { 'test':2 }, 2];
console.log( 'array of obj:', test.reIndexOf(/2/) );

7 thoughts on “Regular Expression in Array.indexOf()

  1. I am so thankful for your code post here. It’s 12:12 in the morning on day 4 of my array problem and your code helped me tremendously! I was losing hope and this solution for finding the piece of the array with a regex statement is just golden!

    Thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *