3

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!

Adam Halasz
  • 57,421
  • 66
  • 149
  • 213

2 Answers2

6

There'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.

Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
  • actually your answer is right, however I just realized that I'm looking for something else http://stackoverflow.com/questions/14480345/regex-how-to-get-the-nth-occurrence-in-a-string – Adam Halasz Jan 23 '13 at 13:01
  • @Adam: You could use my answer together with `strpos` insead of `indexOf`: http://php.net/manual/en/function.strpos.php – Felix Kling Jan 23 '13 at 13:09
  • @Adam: Oops... then just keep using `indexOf` ;) Sorry, got confused for a second. My solution works for strings as well (as long as you don't want to consider word boundaries). Just sayin' :) – Felix Kling Jan 23 '13 at 13:10
2

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143