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.

yoursweater
  • 1,883
  • 3
  • 19
  • 41
  • See https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript for how to compare two arrays for equal elements. – Barmar May 01 '18 at 21:49

1 Answers1

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) )
Hamza El Aoutar
  • 5,292
  • 2
  • 17
  • 23