3

Using ES6 sets, I can do this:

let ints = new Set([1,2,3])
console.log(ints.has(3))

And it prints true because 3 is in the set.

But what about arrays? E.g.

let coordinates = new Set([[1,1], [1,2], [2,0]])
console.log(coordinates.has([1,2]))

this prints false.

As you can see in this CodePen demo

So, without first turning the coordinates into strings (e.g ['1,1', '1,2', '2,0']) how can I work with arrays in sets as if the array was something hashable?

2
  • 7
    Two different objects are never === to each other. Commented Nov 12, 2015 at 15:42
  • 1
    Moreover, it doesn't allow one to customize the equality criteria: stackoverflow.com/questions/29759480/… Commented Nov 12, 2015 at 15:50

1 Answer 1

9

Because Set and Map instances are based on the === comparison (except for NaN), two different arrays will never compare the same and so your example correctly results in false. However:

var a = [1, 1], b = [1, 2], c = [1, 3];
var s = new Set([a, b, c]);
console.log(s.has(a));

will print true.

Sign up to request clarification or add additional context in comments.

Comments

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.