javascript tutorial - [Solved-5 Solutions] Best way to find if an item is in a javascript array? - javascript - java script - javascript array



Problem :

What is the best way to find if an object is in an array? This is the best way We know:

function include(arr, obj) {
    for(var i=0; i<arr.length; i++) {
        if (arr[i] == obj) return true;
    }
}

include([1,2,3,4], 3); // true
include([1,2,3,4], 6); // undefined

click below button to copy the code. By JavaScript tutorial team

Solution 1:

	function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}
click below button to copy the code. By JavaScript tutorial team

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

1. Mozilla's(ECMA-262) version:

  if (!Array.prototype.indexOf)
{

       Array.prototype.indexOf = function(searchElement /*, fromIndex */)

    {


    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
     else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };

}
click below button to copy the code. By JavaScript tutorial team

2. Daniel James's version:

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, fromIndex) {
    if (fromIndex == null) {
        fromIndex = 0;
    } else if (fromIndex < 0) {
        fromIndex = Math.max(0, this.length + fromIndex);
    }
    for (var we = fromIndex, j = this.length; we < j; i++) {
        if (this[i] === obj)
            return i;
    }
    return -1;
  };
}
click below button to copy the code. By JavaScript tutorial team

3. roosteronacid's version:

Array.prototype.hasObject = (
  !Array.indexOf ? function (o)
  {
   var l = this.length + 1;
    while (l -= 1)
    {
        if (this[l - 1] === o)
        {
            return true;
        }
    }
    return false;
  } : function (o)
  {
    return (this.indexOf(o) !== -1);
  }
);

click below button to copy the code. By JavaScript tutorial team

Solution 2:

If we are using jQuery:

$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);
click below button to copy the code. By JavaScript tutorial team

Solution 3:

First, implement indexOf in JavaScript for browsers that don't already have it. For example, see Erik Arvidsson's array extras(also, the associated blog post). And then we can use indexOfwithout worrying about browser support. Here's a slightly optimised version of his indexOfimplementation:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var we = fromIndex, j = this.length; we < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}
click below button to copy the code. By JavaScript tutorial team

It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:

var include = Array.prototype.indexOf ?
    function(arr, obj) { return arr.indexOf(obj) !== -1; } :
    function(arr, obj) {
        for(var we = -1, j = arr.length; ++we < j;)
            if(arr[i] === obj) return true;
        return false;
    };
click below button to copy the code. By JavaScript tutorial team

We prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization WE adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.

Solution 4:

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has',
         {
            value:function(o,flag){
                     if(flag === undefined){
                         return this.indexOf(o) !== -1;
                     }
                     else{   // only for raw js object
                         for(var v in this){
                         if(JSON.stringify(this[v]) === JSON.stringify(o)) return true;
                     }
                      return false;                       
                  },
            // writable:false,
            // enumerable:false
         }
   )
click below button to copy the code. By JavaScript tutorial team

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like          
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false
click below button to copy the code. By JavaScript tutorial team

Solution 5:

It depends on our purpose. If we program for the Web, avoid indexOf, it isn't supported by Internet Explorer 6 (lot of them still used!), or do conditional use:

if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
else result = customSlowerSearch(yourArray, target);
click below button to copy the code. By JavaScript tutorial team

indexOf is probably coded in native code, so it is faster than anything we can do in JavaScript (except binary search/dichotomy if the array is appropriate). Note: it is a question of taste, but WE would do a return false; at the end of our routine, to return a true Boolean...


Related Searches to javascript tutorial - Best way to find if an item is in a javascript array?