Ask coding questions

← Back to all posts
How can I check if a certain array is in a nested array?
HackingGo306 (15)

Let's say I have 2 variables defined as arrays, and I have a third variable. The third variable is a nested array, and it contains the variables:

var array1 = [1,2]
var array2 = [3,4]
var nestedArray = [array1,array2]

In this scenario, I can check if the third array holds array1 or array2 using nestedArray.includes(array1 or 2)
However, if the third array holds the value of the other two but not the variable itself, then nestedArray.includes(array1 or 2) returns false.

If I have the second scenario, how can I check if one of the arrays is in the nested one?

Answered by xxpertHacker (865) [earned 5 cycles]
View Answer
xxpertHacker (865)

Use Array#some and compare value-by-value.

There's no easier way to do it.

For comparing the nested arrays, see

HackingGo306 (15)

So you mean running a for loop and then checking the values?

xxpertHacker (865)

@HackingGo306 I guess they'd be equivalent, but usually the array methods are far more conscise and readable, but yes, that's all you have to do.