[javascript] JavaScript is in array

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?

This question is related to javascript arrays

The answer is


Already answered above but wanted to share.

Will not work in IE though. thanks for mentioning it @Mahmoud

_x000D_
_x000D_
var array1 = [1, 2, 3];_x000D_
_x000D_
console.log(array1.includes(2));_x000D_
// expected output: true_x000D_
_x000D_
var pets = ['cat', 'dog', 'bat'];_x000D_
_x000D_
console.log(pets.includes('cat'));_x000D_
// expected output: true_x000D_
_x000D_
console.log(pets.includes('at'));_x000D_
// expected output: false
_x000D_
_x000D_
_x000D_

got some reference Here. they also have Polyfill for above.


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.


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
}

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');   
}

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:

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

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

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.


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.


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
}

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).


if(array.indexOf("67") != -1) // is in array

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.


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");
    }

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"); 

    }

var myArray = [2,5,6,7,9,6];
myArray.includes(2) // is true
myArray.includes(14) // is false

Just use for your taste:

_x000D_
_x000D_
var blockedTile = [118, 67, 190, 43, 135, 520];_x000D_
_x000D_
// includes (js)_x000D_
_x000D_
if ( blockedTile.includes(118) ){_x000D_
    console.log('Found with "includes"');_x000D_
}_x000D_
_x000D_
// indexOf (js)_x000D_
_x000D_
if ( blockedTile.indexOf(67) !== -1 ){_x000D_
    console.log('Found with "indexOf"');_x000D_
}_x000D_
_x000D_
// _.indexOf (Underscore library)_x000D_
_x000D_
if ( _.indexOf(blockedTile, 43, true) ){_x000D_
    console.log('Found with Underscore library "_.indexOf"');_x000D_
}_x000D_
_x000D_
// $.inArray (jQuery library)_x000D_
_x000D_
if ( $.inArray(190, blockedTile) !== -1 ){_x000D_
    console.log('Found with jQuery library "$.inArray"');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


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".


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
}

Best way to do it in 2019 is by using .includes()

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false

First parameter is what you are searching for. Second parameter is the index position in this array at which to begin searching.

If you need to be crossbrowsy here - there are plenty of legacy answers.


I think the simplest way is that :

(118 in blockedTile); //is true