The Set object is a built-in object in JavaScript that allows you to store unique values of any type. The values can be primitive types such as strings and numbers, or object references.
To create a new Set object, you can use the Set()
constructor:
const mySet = new Set();
You can also pass an iterable object as an argument to the constructor, which will add the values from the iterable to the Set:
const mySet = new Set([1, 2, 3]);
Once you have created a Set, you can add values to it using the add()
method:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
You can check if a value is in a Set using the has()
method:
const mySet = new Set([1, 2, 3]);
console.log(mySet.has(2)); // true
console.log(mySet.has(4)); // false
You can also remove values from a Set using the delete()
method:
const mySet = new Set([1, 2, 3]);
mySet.delete(2);
console.log(mySet.has(2)); // false
You can get the number of values in a Set using the size
property:
const mySet = new Set([1, 2, 3]);
console.log(mySet.size); // 3
You can also use the forEach()
method to iterate over the values in a Set:
const mySet = new Set([1, 2, 3]);
mySet.forEach((value) => {
console.log(value);
});
You can use the Set object to remove duplicates from an array.
For example:
const myArray = [1, 2, 2, 3, 3, 3];
const uniqueValues = new Set(myArray);
console.log(uniqueValues); // Set {1, 2, 3}
You can also convert a Set to an array using the spread operator:
const mySet = new Set([1, 2, 3]);
const myArray = [...mySet];
console.log(myArray); // [1, 2, 3]
The Set object also provides several methods for working with sets mathematically.
For example, you can use the union()
method to create a new Set that contains all the values from two Sets:
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const union = new Set([...set1, ...set2]);
console.log(union); // Set {1, 2, 3, 4}
You can use the intersection()
method to create a new Set that contains only the values that are in both Sets:
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const intersection = new Set([...set1].filter((x) => set2.has(x)));
console.log(intersection); // Set {2, 3}
You can use the difference()
method to create a new Set that contains only the values that are in the first Set but not the second Set:
const set1 = new Set([1, 2, 3]);
const set2 = new Set([2, 3, 4]);
const difference = new Set([...set1].filter((x) => !set2.has(x)));
console.log(difference); // Set {1}
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.