how to check if an element is in a set in javascript

To check if an element is in a set in JavaScript, you can use the has() method of the Set object.

Here is an example code snippet that demonstrates how to use has() method to check if an element is in a set:

index.tsx
// create a new Set object with some elements
let mySet = new Set([1, 2, 3, "hello", "world"]);

// check if 2 is in the Set
if (mySet.has(2)) {
  console.log("2 is in the set");
}

// check if "foo" is in the Set
if (mySet.has("foo")) {
  console.log("foo is in the set");
} else {
  console.log("foo is not in the set");
}
325 chars
15 lines

Alternatively, you can also use the includes() method of the Array object to check if an element is in a set by converting the set to an array:

index.tsx
// convert the Set to an array
let myArray = Array.from(mySet);

// check if 2 is in the array
if (myArray.includes(2)) {
  console.log("2 is in the set");
}

// check if "foo" is in the array
if (myArray.includes("foo")) {
  console.log("foo is in the set");
} else {
  console.log("foo is not in the set");
}
311 chars
15 lines

gistlibby LogSnag