2

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.

1

1 Answer 1

3

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, (i.e 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) )
Sign up to request clarification or add additional context in comments.

4 Comments

careful, this will throw if any element (or segment) is null or undefined
How would I get the index value out of this though? I'd like to be able to see where the matching array is in the array i'm searching
In this case use, findIndex instead of some
@LGSon, I already mentionned this in my answer. (the compareArrays need to be updated depending on the arrays content)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.