JavaScript is in array
JavascriptArraysJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
Try this:
if(blockedTile.indexOf("118") != -1)
{
// element found
}
Solution 2 - Javascript
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
}
Solution 3 - Javascript
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;
};
}
Solution 4 - Javascript
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
}
Solution 5 - Javascript
Underscore.js
UseIt 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');
}
Solution 6 - Javascript
if(array.indexOf("67") != -1) // is in array
Solution 7 - Javascript
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".
Solution 8 - Javascript
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.
Solution 9 - Javascript
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).
Solution 10 - Javascript
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");
}
Solution 11 - Javascript
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.
Solution 12 - Javascript
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
}
Solution 13 - Javascript
var myArray = [2,5,6,7,9,6];
myArray.includes(2) // is true
myArray.includes(14) // is false
Solution 14 - Javascript
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.
Solution 15 - Javascript
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");
}
Solution 16 - Javascript
I think the simplest way is that :
(118 in blockedTile); //is true