2

The following code returns false. What am I doing wrong?

var s = new Set([[1,2], [2,3]])
s.has([2, 3])
false
Alex
  • 2,996
  • 7
  • 31
  • 53
  • 1
    JavaScript defines the equality of objects by their references, not their values. `[2,3] != [2,3]` – 4castle Jun 15 '17 at 05:08
  • Possible duplicate of [How to customize object equality for JavaScript Set](https://stackoverflow.com/questions/29759480/how-to-customize-object-equality-for-javascript-set) – 4castle Jun 15 '17 at 05:16

1 Answers1

0

Because you can't compare objects. [2, 3] === [2, 3] gives false. So you can't find object in set.

Dij
  • 9,501
  • 4
  • 15
  • 34
  • I see. Is there a way to fix this, i.e. converting everything to string? – Alex Jun 15 '17 at 05:12
  • 1
    var s = new Set([String([1,2]), String([2,3])]); s.has(String([2, 3])) will return true. If thats how you wanna use it. – Dij Jun 15 '17 at 05:18
  • 1
    @Alex Not everything in JavaScript can be converted to a string (functions for example), so that won't always work, but in this case it would since you're just storing numbers. – 4castle Jun 15 '17 at 05:19
  • @Alex To be clear, functions do have a `toString` method, but `JSON.toString` removes functions from the output, which is what you'll probably want to use for deep comparison. – 4castle Jun 15 '17 at 05:34