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.
/*
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];
}
};
})();Use it as follows: var s = ["red","green","blue","red","yellow","blue","green","purple","red"];
s.allIndexOf("r"); // result [ -1 ]
s.allIndexOf("red"); // result [ 0,3,8 ]
s.allIndexOf("blue"); // result [ 2,5 ]Try out your own strings in the demo below or full screen.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.