I am coding chess and am wondering how I would check if an array in another array contains x. It would work something like this:
if(array contains array containing x)
CodePudding user response:
You can use flat()
to monodimensionalize the array and includes()
to check.
let x = [0, 1, 2, [3, 4]];
if(x.flat(Infinity).includes(3)) {
console.log("yes");
}
EDIT: Using Infinity
as a parameter, as said in the comments, for multi-level arrays.
CodePudding user response:
If I understood your question you can do something like this
const contains = (data, x) => data.some(d => d.includes(x))
const data1 = [
[1],
[2, 3, 4],
[5]
]
console.log(contains(data1, 1), contains(data1,2), contains(data1, 7))
if you want a recursive approach you can do something like this
const contains = (data, x) => {
if(typeof data !== 'object'){
return data === x
}
return data.some(d => contains(d, x))
}
const data1 = [
[
[1]
],
[2],
[[3, [4]]]
]
console.log(contains(data1, 1), contains(data1, 2),contains(data1, 3),contains(data1, 5))