This array function is an extension of Array.indexOf(), if it exists, and will return all indexes of the search element. It's named allIndexOf(). This code extends javascript and does not require jQuery. It is designed to work in older versions of IE as well, albeit a tiny bit slower.
Originally if you wanted the second instance of a search element, you'd have to call "indexOf" twice. The second time with the starting index of the first result (plus one), or once with a guessed starting index. This should simplify the process for getting any or all of the indexes.
Originally if you wanted the second instance of a search element, you'd have to call "indexOf" twice. The second time with the starting index of the first result (plus one), or once with a guessed starting index. This should simplify the process for getting any or all of the indexes.
/*Use it as follows:
Array.allIndexOf(searchElement)
Array [Array] - the array to search within for the searchElement
searchElement [String] - the desired element with which to find starting indexes
*/
(function(){
Array.prototype.allIndexOf = function(searchElement) {
if (this === null) { return [-1]; }
var len = this.length,
hasIndexOf = Array.prototype.indexOf, // you know, because of IE
i = (hasIndexOf) ? this.indexOf(searchElement) : 0,
n,
indx = 0,
result = [];
if (len === 0 || i === -1) { return [-1]; }
if (hasIndexOf) {
// Array.indexOf does exist
for (n = 0; n <= len; n++) {
i = this.indexOf(searchElement, indx);
if (i !== -1) {
indx = i + 1;
result.push(i);
} else {
return result;
}
}
return result;
} else {
// Array.indexOf doesn't exist
for (n = 0; n <= len; n++) {
if (this[n] === searchElement) {
result.push(n);
}
}
return (result.length > 0) ? result : [-1];
}
};
})();
var s = ["red","green","blue","red","yellow","blue","green","purple","red"];Try out your own strings in the demo below or full screen.
s.allIndexOf("r"); // result [ -1 ]
s.allIndexOf("red"); // result [ 0,3,8 ]
s.allIndexOf("blue"); // result [ 2,5 ]