JavaScript Set Methods
new Set() method
Pass the array to new Set()
Constructor:
Instance
// Create a Set const letters = new Set(["a","b","c"]);
add() method
Instance
letters.add("d"); letters.add("e");
If the same element is added, only the first one will be saved:
Instance
letters.add("a"); letters.add("b"); letters.add("c"); letters.add("c"); letters.add("c"); letters.add("c"); letters.add("c"); letters.add("c");
List Set elements
You can use for..of
Loop through all Set elements (values):
Instance
// Create a Set const letters = new Set(["a", "b", "c"]); // List all elements let text = ""; for (const x of letters) { text += x; }
has() method
If the specified value exists in the Set,has()
The method returns true.
Instance
// Create a Set const letters = new Set(["a", "b", "c"]); // Does the Set contain "d"? answer = letters.has("d");
forEach() method
forEach()
The method calls a function for each element of the Set:
Instance
// Create a Set const letters = new Set(["a", "b", "c"]); // List all entries let text = ""; letters.forEach(function(value) { text += value; });
values() method
values()
The method returns an iterator object containing the values of the Set:
Example 1
// Create a Set const letters = new Set(["a", "b", "c"]); // Get all values const myIterator = letters.values(); // List all values let text = ""; for (const entry of myIterator) { text += entry; }
Example 2
// Create a Set const letters = new Set(["a", "b", "c"]); // List all values let text = ""; for (const entry of letters.values()) { text += entry; }
keys() method
keys()
The method returns an iterator object containing the values of the Set:
Note:
Set has no keys, therefore keys()
Returns with values()
The same content.
This makes Set compatible with Map.
Example 1
// Create a Set const letters = new Set(["a", "b", "c"]); // Create an iterator const myIterator = letters.keys(); // List all elements let text = ""; for (const x of myIterator) { text += x; }
Example 2
// Create a Set const letters = new Set(["a", "b", "c"]); // List all elements let text = ""; for (const x of letters.keys()) { text += x; }
returns an array containing [
entries()
The entries() methodvalue, value].
Note:
entries()
methods are usually used to return the [key, value].
Since Set has no keys, therefore entries()
Returns [value, value].
This makes Set compatible with Map.
Example 1
// Create a Set const letters = new Set(["a", "b", "c"]); // Get all entries const myIterator = letters.entries(); // List all entries let text = ""; for (const entry of myIterator) { text += entry; }
Example 2
// Create a Set const letters = new Set(["a", "b", "c"]); // List all entries let text = ""; for (const entry of letters.entries()) { text += entry; }
Complete Set Reference Manual
For a complete reference, please visit our:JavaScript Set Reference Manual.
This manual includes descriptions and examples of all Set properties and methods.