What you're trying to do won't work because in Javascript you can't compare arrays like that, even if they have the same values. This is because arrays are reference types, not value types, and for reference types Javascript determines whether they are equal or not based on whether they are referencing the same object (i.e. the same place in memory). For instance, just try:
console.log(['a','b'] == ['a','b']); // false
Despite having the same values, each array is a new reference, so they are not equal to each other.
In contrast, the comparison in the code below does involve arrays referencing the same object on both sides of the equation:
let a = ['a','b'];
console.log(a == a); // true
And therefore:
let sello = new Set();
sello.add(a);
console.log(sello.has(a)); // true
To remedy this, you'll want to create a function that compares arrays based on their values. You can first check if the arrays have the same length. If not, then they're not equal. You can then loop through the items in each and see if any are different for any given position. If so, they're not equal. Otherwise, assuming you're dealing with a flat array of primitive values (no nested objects of reference type), then the arrays are equal. This is what I do in 'isEqual' below:
function isEqual(x,y) {
if (x.length != y.length)
return false;
for (let i in x)
if (x[i] != y[i])
return false;
return true;
}
Test it if you like:
console.log(isEqual(['a','b'],['a','b'])); // true
Now, unfortunately, Set.has()
doesn't accept a function, so we can't use it with isEqual
. But you can just loop through the values of the set. If creating a one-liner is the goal, the best way I have found to do this is to convert the set to an array and use the some
method. some
accepts a function that evaluates each row, and if it returns true for any row, then the result is true, else false.
console.log(
[...sello].some(item => isEqual(item, ['a','b']))
);
// true