Friday, March 16, 2007

Array Search Prototype

from DZone Snippets: javascript code by pcx99 (Patrick)
This 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 if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}

No comments :