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?
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.
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.
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.
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'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With