Let's say I have this array:
var a = [1,2,99,3,4,99,5];
I would like to get the position of the second 99
, something like:
a.indexOf(99, 2) // --> 5
However the second argument in indexOf
just tells where to start the search. Is there any built in functions to make this? If not how would you do it?
Thanks!
Let's say I have this array:
var a = [1,2,99,3,4,99,5];
I would like to get the position of the second 99
, something like:
a.indexOf(99, 2) // --> 5
However the second argument in indexOf
just tells where to start the search. Is there any built in functions to make this? If not how would you do it?
Thanks!
Share Improve this question edited Jan 23, 2013 at 12:28 Adam Halasz asked Jan 23, 2013 at 12:21 Adam HalaszAdam Halasz 58.3k67 gold badges153 silver badges216 bronze badges 1-
a.indexOf(99, a.indexOf(99)+1)
– John Dvorak Commented Jan 23, 2013 at 12:26
2 Answers
Reset to default 6There's only indexOf
and lastIndexOf
. You could loop over it:
var a = [1,2,99,3,4,99,5];
var matches = []
for (var i=0; i<a.length; i++){
if (a[i] == 99) {
matches.push(i)
}
}
console.log(matches); // [2, 5]
If you always want the second occurrence Jan's method is also good:
a.indexOf(99, a.indexOf(99) + 1)
The indexOf
call on the right finds the first occurrence, +1
then limits the search to the elements that follow it.
There is no built in function, but you can easily create your own, by iteratively applying indexOf
:
function indexOfOccurrence(haystack, needle, occurrence) {
var counter = 0;
var index = -1;
do {
index = haystack.indexOf(needle, index + 1);
}
while (index !== -1 && (++counter < occurrence));
return index;
}
// Usage
var index = indexOfOccurrence(a, 99, 2);
But Matt's solution might be more useful.