Check if an element exists in a set in JavaScript
This post will discuss how to check if an element exists in a set in JavaScript.
There are several ways to check if an element is present in a set in JavaScript. A set is a data structure that stores unique values of any type. To check if a set contains a specific element, we can use the following functions:
1. Using Set.has() function
This function returns a boolean value indicating whether an element with the specified value exists in the set or not. To use it, we need to call the has() function on the set object with the value as an argument. This will return true if the value is found in the set, and false otherwise. For instance:
|
1 2 3 4 5 6 |
// Create a new set using the Set constructor var mySet = new Set([1, 5, "some text"]); // Check if the set contains 5 and "hello" using the has function console.log(mySet.has(5)); // true console.log(mySet.has("hello")); // false |
2. Using Array.includes() function
We can convert the set into an array using the spread syntax (…) or the Array.from() function, and then call the Array.includes() function on the array with the value as an argument. The includes() function determines whether an array includes a specified value among its entries, returning true or false as appropriate. For instance:
|
1 2 3 4 5 6 7 8 9 |
// Create a new set using the Set constructor var mySet = new Set([1, 5, "some text"]); // Convert the set into an array using Array.from var myArray = Array.from(mySet); // [...mySet] // Check if the set contains 5 and "hello" using the includes function console.log(myArray.includes(5)); // true console.log(myArray.includes("hello")); // false |
3. Using a custom function
Finally, we can create a custom function that iterates over the set using the for…of loop, compare each element with the value we are looking for, and return true if it matches. If the loop ends without finding a match, return false. Here’s an example of how we can achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Define a function that takes a set and a value as parameters function hasElement(set, value) { // Loop over each element in the set for (const element of set) { // Return true if the element matches the value if (element === value) { return true; } } // Return false if no match is found return false; } // Create a new set using the Set constructor var mySet = new Set([1, 5, "some text"]); // Check if the set contains 5 and "hello" using the has function console.log(hasElement(mySet, 5)); // true console.log(hasElement(mySet, "hello")); // false |
That’s all about checking if an element exists in a set in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)