Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean operations on sets of arrays in JavaScript

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?

like image 539
Peter Bengtsson Avatar asked Dec 18 '25 20:12

Peter Bengtsson


1 Answers

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.

like image 98
Pointy Avatar answered Dec 20 '25 13:12

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!