Design & Download
Your JS Library
in Seconds!!!

Snippet: nthIndexOf() - Find the Nth Occurrence Of A Target

Written by Christopher West (cwest) on December 31, 2015.
Find the nth occurrence of a target within an array (or array-like object), a string or an object, going in order or in reverse order.
function nthIndexOf(subject, target, n) {
  var i, tLen,
      indices = [],
      nIsNegative = n < 0,
      fnName = (nIsNegative ? 'lastI' : 'i') + 'ndexOf',
      l = subject.length,
      increment = nIsNegative ? -1 : 1;
  if (n = ~~n) {
    if (isArrayLike(subject)) {
      for (i = nIsNegative ? l - 1 : 0; nIsNegative ? i >= 0 : (i < l); i += increment) {
        if (target === subject[i] && !(n -= increment)) {
          return i;
        }
      }
      return -1;
    }
    else if (typeOf(subject, 'String')) {
      if (typeOf(target, 'RegExp')) {
        target = flagRegExp(target, 'g');
        subject.replace(target, function(a) {
          a = arguments;
          indices.push(a[a.length - 2]);
        });
        return increment * n <= indices.length ? indices.slice(nIsNegative ? n : ~-n)[0] : -1;
      }
      else {
        subject = subject.split(target);
        return subject[n * increment] != undefined ? subject.slice(0, n).join(target).length : -1;
      }
    }
    else {
      for (i in subject) {
        if (target === subject[i]) {
          n -= increment;
          if (nIsNegative) {
            indices.push(i);
          }
          else if (!n) {
            return i;
          }
        }
      }
      if (n < indices.length) {
        return indices[n];
      }
    }
  }
}

nthIndexOf(...) API Documentation

Find the nth occurrence of a target within an array (or array-like object), a string or an object, going in order or in reverse order.

Parameters

  1. subject {Array|Object|string}:
    The array (or array-like object), string or object to traverse in order to find the index of the nth occurrence of target.
  2. target {*}:
    • If subject is a string, this can either be a RegExp or a string. If this is a RegExp it will be used to find all of the matching substrings by adding the global flag to its clone. If this is a string, this substring will be searched for within subject.
    • If subject is a Array (or Array-like) or an Object, this can be anything for which to search for within subject at each index (or key).
  3. n {number}:
    If this is a positive number it represents the number of the occurrence going from beginning to end for which the index (or key) should be returned. If this is a negative number it represents the occurrence going from end to beginning for which the index (or key) should be returned. NOTE: If this is not a finite number other than 0 the returned value will be undefined.

Returns

If searching a string or an array and the nth occurrence is found the index at which that occurrence of subject is found will be returned. If searching a string or an array and the nth occurrence isn't found -1 will be returned. If searching an object which is not array-like and the occurrence is found the corresponding key will be returned. In all other cases undefined will be returned. If n is not a finite number other than 0, undefined will be returned.