1

this might be a duplicate but I couldn't find a solution. If I have an array of arrays, is there a "built-in" way to determine if that array of arrays includes another array. Array.prototype.includes() helps, but doesn't get me all the way because of (I think) object references as shown below. I can manually test equality of each value but I'm sure there's a better way.

$ node
> b = [[1,2,3]]
[ [ 1, 2, 3 ] ]
> b[0]
[ 1, 2, 3 ]
> b.includes(b[0])
true
> b.includes([1,2,3])
false
> 
5
  • direct comparison. Does b contain the exact array [1,2,3]? Commented Dec 28, 2019 at 15:37
  • 3
    Note that in JavaScript [1,2,3] !== [1,2,3]. They are different arrays. Commented Dec 28, 2019 at 15:38
  • Well the answer is there already but I would use .toString() instead Commented Dec 28, 2019 at 15:41
  • @Saurav Is .toString() more performant? Commented Dec 28, 2019 at 15:42
  • .toString() would not work really with nested array (e.g. [1,2,[3,4]].toString() == [[1],2,[3],[[4]]].toString(). Or when the array contains , ([1,'2,3'].toString()==[1,2,3].toString()) Commented Dec 28, 2019 at 15:52

1 Answer 1

3

I recommend to use JSON.stringify & includes.

JSON.stringify([[1,2,3]]).includes(JSON.stringify([1,2,3]))
true
JSON.stringify([[1,3]]).includes(JSON.stringify([1,2,3]))
false
Sign up to request clarification or add additional context in comments.

2 Comments

While this may be a quick and dirty solution, this has some pitfalls. To give an example: JSON.stringify([[_ => 0]]).includes(JSON.stringify([null]))
@ASDFGerte you are right, but it's only a case where the array contains functions. It's safe to use if he can assume the array contains only numbers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.