210

Let's say I have this:

var blockedTile = new Array("118", "67", "190", "43", "135", "520");

There's more array elements but those are just few for readability purposes. Anyways, I could do a "for" loop but it would do 500 loops everytime you click on the map... is there any other way to see if a certain string is in an array?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
test
  • 17,706
  • 64
  • 171
  • 244

16 Answers16

317

Try this:

if(blockedTile.indexOf("118") != -1)
{  
   // element found
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • 25
    This doesn't work for old browsers (like IE < 9). There's a jQuery function for this: http://api.jquery.com/jQuery.inArray/ – Vinicius Braz Pinto Oct 05 '12 at 14:42
  • 5
    A faster way is to flip the bit wise `if(!!~blockedTile.indexOf('118))` this method will always return true if the result > -1 and false if result === -1 – bm_i Nov 05 '12 at 19:01
  • 14
    @bm_i Which *faster*? Faster to type? – alex Oct 02 '13 at 20:01
  • 3
    `indexOf()` can also be applied on literal arrays, e.g. `if (-1 == [84, 116].indexOf(event.keyCode))`. Tested on Chrome 37.0.2062.122. – François Sep 24 '14 at 16:58
  • 2
    fwiw I always use `indexOf(…) >= 0`. makes no difference and i forget where i picked it up as a habit – JSDBroughton Mar 08 '16 at 12:10
  • can't we use ('118' in blockedTile) in javascript? – prabhat mishra Mar 01 '18 at 07:14
  • 1
    @prabhatmishra. Unfortunately, no. The `in` operator checks for keys, not values. It would work for `"118" in { "118": "bla" }`, but not for `"118" in [ "118" ]`. It would work for `0 in [ "118" ]`, though, since "118" has a key of 0. If modern JavaScript (ES2016+) is not an object, I'd recommend using `includes()` over `indexOf()`, though, as it's easier to understand and less effort to type. – Nolonar Aug 05 '21 at 20:33
104

As mentioned before, if your browser supports indexOf(), great! If not, you need to pollyfil it or rely on an utility belt like lodash/underscore.

Just wanted to add this newer ES2016 addition (to keep this question updated):

Array.prototype.includes()

if (blockedTile.includes("118")) {
    // found element
}
Kutyel
  • 8,575
  • 3
  • 30
  • 61
14

Some browsers support Array.indexOf().

If not, you could augment the Array object via its prototype like so...

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) // shortcut for verifying if it's NaN
        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;
  };
}

Source.

alex
  • 479,566
  • 201
  • 878
  • 984
13
function in_array(needle, haystack){
    var found = 0;
    for (var i=0, len=haystack.length;i<len;i++) {
        if (haystack[i] == needle) return i;
            found++;
    }
    return -1;
}
if(in_array("118",array)!= -1){
//is in array
}
ndhanhse
  • 154
  • 1
  • 4
11

Use Underscore.js

It cross-browser compliant and can perform a binary search if your data is sorted.

_.indexOf

_.indexOf(array, value, [isSorted]) Returns the index at which value can be found in the array, or -1 if value is not present in the array. Uses the native indexOf function unless it's missing. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search.

Example

//Tell underscore your data is sorted (Binary Search)
if(_.indexOf(['2','3','4','5','6'], '4', true) != -1){
    alert('true');
}else{
    alert('false');   
}

//Unsorted data works to!
if(_.indexOf([2,3,6,9,5], 9) != -1){
    alert('true');
}else{
    alert('false');   
}
Brandon Boone
  • 16,281
  • 4
  • 73
  • 100
6
if(array.indexOf("67") != -1) // is in array
Marty
  • 39,033
  • 19
  • 93
  • 162
5

IMHO most compatible with older browsers

Array.prototype.inArray = function( needle ){

    return Array(this).join(",").indexOf(needle) >-1;

}

var foods = ["Cheese","Onion","Pickle","Ham"];
test = foods.inArray("Lemon");
console.log( "Lemon is " + (test ? "" : "not ") + "in the list." );

By turning an Array copy in to a CSV string, you can test the string in older browsers.

David
  • 5,882
  • 3
  • 33
  • 44
Mark Giblin
  • 1,086
  • 2
  • 13
  • 20
  • 4
    this will false positive if any of the array members contained the needle but were not exclusively it. e.g. `['Lemon Pie'].inArray('Lemon')` will return `True`. You may wrap needle with `,` to get around it or use regex matching to do likewise but join would be preferable using something more obscure than `,` for similar false-positive reasons (`|` say). It depends on the dataset – JSDBroughton Mar 08 '16 at 12:05
5

Assuming that you're only using the array for lookup, you can use a Set (introduced in ES6), which allows you to find an element in O(1), meaning that lookup is sublinear. With the traditional methods of .includes() and .indexOf(), you still may need to look at all 500 (ie: N) elements in your array if the item specified doesn't exist in the array (or is the last item). This can be inefficient, however, with the help of a Set, you don't need to look at all elements, and instead, instantly check if the element is within your set:

const blockedTile = new Set(["118", "67", "190", "43", "135", "520"]);

if(blockedTile.has("118")) {
  // 118 is in your Set
  console.log("Found 118");
}

If for some reason you need to convert your set back into an array, you can do so through the use of Array.from() or the spread syntax (...), however, this will iterate through the entire set's contents (which will be O(N)). Sets also don't keep duplicates, meaning that your array won't contain duplicate items.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
4

I'd use a different data structure, since array seem to be not the best solution.

Instead of array, use an object as a hash-table, like so:

(posted also in jsbin)

var arr = ["x", "y", "z"];
var map = {};
for (var k=0; k < arr.length; ++k) {
  map[arr[k]] = true;
}

function is_in_map(key) {
  try {
    return map[key] === true;
  } catch (e) {
    return false;
  }
}


function print_check(key) {
  console.log(key + " exists? - " + (is_in_map(key) ? "yes" : "no"));
}

print_check("x");
print_check("a");

Console output:

x exists? - yes
a exists? - no

That's a straight-forward solution. If you're more into an object oriented approach, then search Google for "js hashtable".

Ron Klein
  • 9,178
  • 9
  • 55
  • 88
3

Depending on the version of JavaScript you have available, you can use indexOf:

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

Or some:

Tests whether some element in the array passes the test implemented by the provided function.

But, if you're doing this sort of existence check a lot you'd be better of using an Object to store your strings (or perhaps an object as well as the Array depending on what you're doing with your data).

mu is too short
  • 426,620
  • 70
  • 833
  • 800
2

Why don't you use Array.filter?

var array = ['x','y','z'];
array.filter(function(item,index,array){return(item==YOURVAL)}).

Just copy that into your code, and here you go:

Array.prototype.inArray = function (searchedVal) {
return this.filter(function(item,index,array){return(item==searchedVal)}).length==true
}
2

in array example,Its same in php (in_array)

 var ur_fit = ["slim_fit", "tailored", "comfort"];
 var ur_length = ["length_short", "length_regular", "length_high"];
    if(ur_fit.indexOf(data_this)!=-1){
        alert("Value is avail in ur_fit array");
    }
    else if(ur_length.indexOf(data_this)!=-1){      
         alert("value is avail in ur_legth array"); 

    }
Avinash Raut
  • 1,872
  • 20
  • 26
2
var myArray = [2,5,6,7,9,6];
myArray.includes(2) // is true
myArray.includes(14) // is false
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
kaboome
  • 41
  • 1
  • 4
    Posting a piece of code is **NOT** an answer, you should add explanations on top of that. – N.K Jun 01 '18 at 08:31
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Luca Kiebel Jun 01 '18 at 10:09
  • There are already several answers suggesting to use `includes`. How does this answer provide any additional values compared to them? – Boghyon Hoffmann Jun 01 '18 at 10:16
  • programming in various languages one might just forget how to spell a simple command in one of them... this snippet was what got me here from ‘in_array js’ so I guess it is helpful @Beghyon – Maciek Rek Aug 14 '22 at 06:25
0

You can try below code. Check http://api.jquery.com/jquery.grep/

var blockedTile = new Array("118", "67", "190", "43", "135", "520");
var searchNumber = "11878";
arr = jQuery.grep(blockedTile, function( i ) {
  return i === searchNumber;
});
if(arr.length){ console.log('Present'); }else{ console.log('Not Present'); }

check arr.length if it's more than 0 means string is present else it's not present.

Prasad Wargad
  • 737
  • 2
  • 7
  • 11
0

a little bit code from my side (custom function for Array):

    Array.prototype.in_array = function (array) {
        var $i = 0;
        var type = typeof array;
        while (this[$i]) {
            if ((type == ('number') || type == ('string'))  && array == this[$i]) {
                return true;
            } else if (type == 'object' && array instanceof Array && array.in_array(this[$i])) {
                return true
            }
            $i++;
        }
        return false;
    };


    var array = [1, 2, 3, "a", "b", "c"];

    //if string in array
    if (array.in_array('b')) {
        console.log("in array");
    }

    //if number in array
    if (array.in_array(3)) {
        console.log("in array");
    }

    // if one from array in array
    if (array.in_array([1, 'b'])) {
        console.log("in array");
    }
Eugen
  • 1,356
  • 12
  • 15
-5

I think the simplest way is that :

(118 in blockedTile); //is true