JavaScript Sets
In JavaScript, a set, like an array, is a special type of variable that can hold multiple values of the same type. What distinguishes sets from arrays however, is that sets hold unique values, whereas arrays can contain duplicates.
The below example creates an empty set called 'fname' and then adds three names using the 'add' method.
let fname = new Set(); fname.add("Bob"); fname.add("Fred"); fname.add("George");
A set can also be declared and initialised in one statement.
let fname = new Set(["Bob", "Fred", "George"]);
If an attempt is made to add a duplicate value into a set, no error is produced, it just doesn't get added.
Unlike with an array, where each item within can be referred to by its index value, a set doesn't have an index associated with it, so individual values are not accessible. This also means that it is not possible to use an ordinary 'for' loop to iterate through a set, however, the variation of it, as shown previously with arrays, can be used.
for (let name of fname) { document.write(name + "<br />"); }
This will produce the following output.
Bob Fred George
The items are displayed in the order that they were added to the set.
If it is necessary to find out the number of values within a set, the 'size' property can be used.
document.write(fname.size);
In order to check if a set contains a particular value, the 'has' method can be utilised.
if (fname.has("Fred"))
{
document.write("Fred is in the set.");
}
The 'delete' method can be used to remove a particular value from a set.
fname.delete("Fred");
Finally, if it is necessary to remove all the values in a set, this can be achieved with the 'clear' method.
fname.clear();