0

I'm wondering what the best way to determine the membership of one array in another array in JS.

Here's an example

let a = [];
a.push([1,2]);
a.includes([1,2]) <- evaluates to false
a.indexOf([1,2]) <- evaluates to -1

What's the deal here? Any efficient work around?

Tim Carew
  • 11
  • 1
  • 5

1 Answers1

0

At the moment, your search array doesn't actually equal the array within your a array as they have 2 different references in memory. However, you could convert your arrays to strings, such that your search can equal another string array within your array.

To do this you could convert your inner arrays to string using .map(JSON.stringify) and then search for the string version of your array using .includes(JSON.stringify(search_arrr)).

See example below:

let a = [];
let search = [1, 2];
a.push([1,2]);

a = a.map(JSON.stringify)
console.log(a.includes(JSON.stringify(search)));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64