Array Search Prototype
Join the DZone community and get the full member experience.
Join For FreeThis prototype extends the Array object to allow for searches
within the Array. It will return false if nothing is found. If
item(s) are found you'll get an array of indexes back which matched
your search request. It accepts strings, numbers, and regular expressions as search
criteria. 35 is different than '35' and vice-versa.
// Examples
var test=[1,58,'blue','baby','boy','cat',35,'35',18,18,104]
result1=test.find(35); //returns 6
result2=test.find(/^b/i); //returns 2,3,4
result3=test.find('35'); //returns 7
result4=test.find(18); // returns 8,9
result5=test.find('zebra'); //returns false
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i
Prototype
Data structure
Opinions expressed by DZone contributors are their own.
Comments