Design & Download
Your JS Library
in Seconds!!!

Snippet: findIndex() - Callback Based Index Of

Written by Christopher West (cwest) on December 04, 2015.
Gets the first index (or key) at which a callback function returns a truthy value.
function findIndex(arrOrObj, fn, opt_searchAll) {
  fn = getSimpleCallback(fn);
  var k = 0, l;
  if (isArrayLike(arrOrObj)) {
    for (l = arrOrObj.length; k < l; k++) {
      if ((opt_searchAll || has(arrOrObj, k)) && fn(arrOrObj[k], k, arrOrObj)) {
        return k;
      }
    }
    return -1;
  }
  else {
    for (k in arrOrObj) {
      if ((opt_searchAll || has(arrOrObj, k)) && fn(arrOrObj[k], k, arrOrObj)) {
        return k;
      }
    }
  }
}

findIndex(...) API Documentation

Gets the first index (or key) at which a callback function returns a truthy value.

Parameters

  1. arrOrObj {Array|Object}:
    This is the array or object whose values will be traversed to find the first index at which the specified callback function returns a truthy value.
  2. fn {Function}:
    The callback function that will be called for each value in arrOrObj until it returns something truthy. The following parameters will be passed to it on each iteration:
    1. value:
      The value within arrOrObj to be tested.
    2. index:
      The index (or key) of the value within arrOrObj to be tested.
    3. arrOrObj:
      The array or object be traversed.
  3. opt_searchAll {boolean=}:
    Optional. Defaults to false. If false only the indices or keys that are actually owned by arrOrObj will be traversed. If true all of the values will be traversed regardless of if they are owned by arrOrObj.

Returns

The index (or key) at which the callback function (fn()) returned a truthy value. If the callback function never returns a truthy value and arrOrObj is an array or array-like, -1 will be returned. If the callback function never returns a truthy value and arrOrObj is not array-like, undefined will be returned.