Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether an array exists in an array of arrays?

Tags:

javascript

I'm using JavaScript, and would like to check whether an array exists in an array of arrays.

Here is my code, along with the return values:

var myArr = [1,3]; var prizes = [[1,3],[1,4]]; prizes.indexOf(myArr); -1 

Why?

It's the same in jQuery:

$.inArray(myArr, prizes); -1 

Why is this returning -1 when the element is present in the array?

like image 713
Richard Avatar asked Oct 23 '13 13:10

Richard


People also ask

How do you check if an array is within an array?

if u need to see if an array exists just calculate the hash o(n) and lookup o(1). hash function can be as simple as concatinating all the elements with '-' , if your array size is huge, make a number from that array ([1,2] => 12) , and use mod of a big prime number, for collision chain them.

How do you check if there is an array inside an array JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do I check if an array exists?

length property: The array can be check if it is actually an array and it exists by the Array. isArray() method. This method returns true if the Object passed as a parameter is an array. It also checks for the case if the array is undefined or null.


1 Answers

You can use this

 var a = [ [1,2] , [3,4] ];  var b = [1,2];  a = JSON.stringify(a);  b = JSON.stringify(b); 

then you can do just an indexOf() to check if it is present

var c = a.indexOf(b); if(c != -1){     console.log('element present'); } 
like image 187
ajack13 Avatar answered Oct 14 '22 11:10

ajack13