3

If I have an array const a = [1, 2] and a nested array const nested = [[1,2], [2,3]]

How do I check if array a is in the nested?

I tried using the nested.includes(a), but it doesn't provide the correct output. And I was thinking stringify the array a, but read some comments about we should not compare array using stringify.

So what is a proper way to check if an array is in another array?

Boogie
  • 115
  • 6
  • Well, strictly speaking two different arrays are *different* and not equal. You'll have to come up with your own criteria for how to perform the comparisons based on array content. For example, does order matter? It might, or it might not. – Pointy Aug 11 '21 at 19:24
  • Does this answer your question? [How to check if an array contains another array?](https://stackoverflow.com/questions/41661287/how-to-check-if-an-array-contains-another-array) – Gangula Nov 17 '22 at 08:06

3 Answers3

2

includes doesn't work correctly as it compares references - a and nested[0] are different in terms of references.

Take a look at following function:

function includesDeep(array, value) {
  return array.some((subArray) => {
    return subArray.every(
      (subArrayElem, index) => subArrayElem === value[index]
    );
  });
}

We have to iterate over all elements of given array and check if every element of this sub array is identical to corresponding element from second array (your a). This method detects type mismatches.

Aitwar
  • 839
  • 4
  • 11
1

You can stringify the arrays to compare whether they are equal in the callback of Array.some :

const a = [1, 2]
const nested = [[1,2], [2,3]]
const containsA = nested.some(e => JSON.stringify(e) == JSON.stringify(a))
console.log(containsA);
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 2
    One problem. Try this: `const a = ['1', 2]`. It will pass as `toString` doesn't mark strings. – Aitwar Aug 11 '21 at 19:26
-1

if you must compare it without stringification, prepend a unique id to the values and compare that.

PartialFlavor_55KP
  • 137
  • 1
  • 3
  • 13