简体   繁体   中英

How to check to see if there's an array within an array?

The Problem

I want to test for the presence of an array inside of an array. For example, if my array is this:

let arr = ["all", ['>', 'PSF', 10]]

I want something like this to work:

let segment = ['>', 'PSF', 10]
arr.indexOf(segment) // would be equal to 1, in this case

What actually happens

arr.indexOf(segment) is currently -1, since I believe in JavaScript [] != [] due to the way it checks the array memory location.

At any rate, what would be the recommended way of testing to see if a specific array currently exists within an array? I also tried .includes(), but it seems to work the same way that indexOf works (so it failed).

Any help would be appreciated.

You first need to create a function that compare 2 arrays, (the implementation will depend on your needs) , for example :

const compareArrays = (a1, a2) => Array.isArray(a1) && Array.isArray(a2) && a1.length === a2.length && a1.every((v, i) => v === a2[i])

You will need to define this function, because your array segment , may be more complicated, (ie contains other arrays)

Then use some to check whether your original array contains the array ( segment ) :

arr.some(element => compareArrays(segment, element) )

Or findIndex , to get the index of the matching array (or -1 if no matching array exists)

arr.findIndex(element => compareArrays(segment, element) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM