Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a Set contains a list in Javascript

I have a set that I've added a list to.

var a = new Set();
a.add([1]);

Now I check if [1] exists in a:

a.has([1]);
> false

Based on the spec, this might be happening because if type is same for two objects being compared:

Return true if x and y refer to the same object. Otherwise, return false.

And this also happens:

[1] == [1]; 
> false

So it might be that the Set .has() is using == for comparing equality (not sure though). Is there a .contains() method for Set() in JS like Java has?

like image 946
ShivanKaul Avatar asked Aug 15 '16 23:08

ShivanKaul


People also ask

How do you check if a Set contains an element in JavaScript?

The Set.has() method in JavaScript is used to check whether an element with a specified value exists in a Set or not. It returns a boolean value indicating the presence or absence of an element with a specified value in a Set.

How do you check if an object is in a list JavaScript?

Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.

Which method is used to check if a value exists in a Set?

contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element.

How do you check if an item exists in an array JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.


2 Answers

You can't compare references like arrays and objects for equality (you can compare values, though).

The way you're doing it, you're checking against a different reference, even though the values appear to be the same.

Do something like this:

var a = new Set();
var b = [1];

a.add(b);

a.has(b); // => true

Take a look at MDN's Equality comparisons and sameness.

So it might be that the Set .has() is using == for comparing equality (not sure though)

Not necessarily. [1] === [1] (using the strict equality operator) also returns false.

Is there a .contains() method for Set() in JS like Java has?

Not in the way you're imagining it. You can do some sort of deep comparison, as mentioned in the first link in this answer.

like image 182
Josh Beam Avatar answered Oct 09 '22 03:10

Josh Beam


although both [1]'s have the same value, they are two different arrays, pointing to two different locations in memory, hence they are not equal.

you can use a basic loop to check

for (let item of mySet.keys()) {
  item.toString() == [1].toString();
  //true on match.
}
like image 32
Bamieh Avatar answered Oct 09 '22 04:10

Bamieh