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/) );
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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Glad it helped.
+1 for this helpful code snippet.
This saved me loads!! Thanks!
Thanks, that helped me.
But I think better idea will be use loop ‘for’ insead of ‘for in’.
Like this:
https://jsfiddle.net/LLmncx30/
Here’s explanation:
http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea
This is so helpful, the concept should be added to the ECMA Script spec ;)
Well done sir, well done :cheers:
Brilliant!!… I needed! And… I learned of Prototype.
Thanks!.