Sets
In JavaScript, a Set is a built-in data structure that represents an unordered collection of unique values. Sets can be used to efficiently remove duplicates from an array, perform set operations such as union, intersection, and difference, and check if a value is a member of a set.
Here is an example of using a Set in JavaScript:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet); // Output: Set { 1, 2, 3 }
mySet.add(2);
console.log(mySet); // Output: Set { 1, 2, 3 }
mySet.delete(2);
console.log(mySet); // Output: Set { 1, 3 }
console.log(mySet.has(1)); // Output: true
console.log(mySet.size); // Output: 2
mySet.clear();
console.log(mySet); // Output: Set {}
In this example, we create a new Set object called mySet using the new Set() constructor. We add several values to the set using the add() method, which only adds a value if it doesn't already exist in the set. We then use the delete()method to remove a value from the set and the has() method to check if a value is a member of the set. The sizeproperty returns the number of elements in the set. Finally, we use the clear() method to remove all elements from the set.
Sets can also be used to perform set operations, such as union, intersection, and difference. Here is an example of using the Set object to perform a union operation:
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const unionSet = new Set([...set1, ...set2]);
console.log(unionSet); // Output: Set { 1, 2, 3, 4 }
In this example, we create two Set objects, set1 and set2, and use the spread operator to create a new set that contains all the elements of both sets. The resulting set, unionSet, contains the elements 1, 2, 3, and 4.
Sets are a useful data structure for efficiently storing and manipulating collections of unique values in JavaScript.