Design & Download
Your JS Library
in Seconds!!!

Snippet: indexOf()

Written by Christopher West (cwest) on November 07, 2015.
Finds the index of a specified value in an array (or array-like object) or an object.
function indexOf(obj, target, opt_fromIndex) {
  if (isArrayLike(obj)) {
    for (var i = opt_fromIndex ? opt_fromIndex < 0 ? Math.max(0, obj.length + opt_fromIndex) : opt_fromIndex : 0, l = obj.length; i < l; i++) {
      if (has(obj, i) && obj[i] === target) {
        return i;
      }
    }
    return -1;
  }
  else if (typeOf(obj = Object(obj), 'String')) {
    return obj.indexOf(target + '', opt_fromIndex);
  }
  for (var key in obj) {
    if (has(obj, key) && obj[key] === target) {
      return key;
    }
  }
}

ECMAScript 6 introduced some new array function. One of them is Array.prototype.indexOf(). Unfortunately, as is normal when writing in JS, we cant assume that everyone and their grandmom is using a browser that has this function defined. Also, at times we may want to find the property name of an object with a specific value. That is the reason I wrote indexOf() for YourJS.

Documenation

Parameters

  1. obj {Array|Object|string}:
    The array, object or string that will be searched.
  2. target {*}:
    The thing be searched for within obj.
  3. opt_fromIndex {number}:
    Optional. Defaults to 0. When searching an array or a string, this is indicates the starting index in the search. When searching an array, a negative value will start that many positions from the end.

Return

If obj is an Array (or Array-like) or a string the return value will be a non-negative integer if target was found or-1 if not found. If obj is an Object the return value will be a string if target is found. In all other cases the return value will be undefined.