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?

Peter Bengtsson
  • 6,067
  • 8
  • 39
  • 51
  • 7
    Two different objects are never `===` to each other. – Pointy Nov 12 '15 at 15:42
  • 1
    Moreover, it doesn't allow one to customize the equality criteria: http://stackoverflow.com/questions/29759480/how-to-customize-object-equality-for-javascript-set – Haroldo_OK Nov 12 '15 at 15:50

1 Answers1

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.

Pointy
  • 371,531
  • 55
  • 528
  • 584