I want to know whether if an array is inside of a 2D array.
This is what I tried:
var x=[1,2];
var y=[[1,1],[1,2],[2,2],[3,3]];
y.includes(x); //should return true
you can create a hash:
var ar = [
[1,1],[1,2],[2,2],[3,3]
];
var hash = {};
for(var i = 0 ; i < ar.length; i += 1) {
hash[ar[i]] = i;
}
var val = [1,2];
if(hash.hasOwnProperty(val)) {
document.write(hash[val]);
}
["1", "2"] and [1,2] - not sure if that matters for this case. +1 either way.You can do this with chained array methods!
var ar = [
[1,1],[1,2],[2,2],[3,3]
];
hasDuplicates(ar, [1,"1"]); //false
hasDuplicates(ar, [1,1]); //true
//Use some to determine at least 1 inner array matches
function hasDuplicates(array, valueToCheck) {
return array.some(function(a, i) {
//Check each inner arrays index, and verify that it equals on the same index of the array we want to check
return a.every(function(ax, ix) {
return valueToCheck[ix] === ax; //triple equals for equality!
})
});
}
[1,2] !== [1,2]so you can't directly compare them as objects_.findIndex(y, x)which would return the position insideyunderscorejs.org/#findIndex, or you could make it a truth test with_.findIndex(y,x) >== 0