I needed 2d arrays, so I made a nested array since JavaScript doesn't allow them.
They look like this:
var myArray = [
[1, 0],
[1, 1],
[1, 3],
[2, 4]
]
How can I check if this array includes a specific element (i.e. one of these [0,1]
arrays) in vanilla JS?
Here is what I tried, with no success (everything returns false
) (EDIT: I included the answers in the snippet):
var myArray = [
[1, 0],
[1, 1],
[1, 3],
[2, 4]
]
var itemTrue = [2, 4];
var itemFalse = [4, 4];
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
// EDIT: first answer's solution
function isArrayInArray(x, check) {
for (var i = 0, len = x.length; i < len; i++) {
if (x[i][0] === check[0] && x[i][1] === check[1]) {
return true;
}
}
return false;
}
// EDIT: accepted answer's solution
function isArrayInArray2(x, check) {
var result = x.find(function(ele) {
return (JSON.stringify(ele) === JSON.stringify(check));
})
return result !=null
}
console.log("true :" + myArray.includes(itemTrue));
console.log("false :" + myArray.includes(itemFalse));
console.log("true :" + (myArray.indexOf(itemTrue) != -1));
console.log("false :" + (myArray.indexOf(itemFalse) != -1));
console.log("true :" + contains(myArray, itemTrue));
console.log("false :" + contains(myArray, itemFalse));
// EDIT: first answer's solution
console.log("true :" + isArrayInArray(myArray, itemTrue));
console.log("false :" + isArrayInArray(myArray, itemFalse));
// EDIT: accepted answer's solution
console.log("true :" + isArrayInArray2(myArray, itemTrue));
console.log("false :" + isArrayInArray2(myArray, itemFalse));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…