We will use a sample program to explain how to use JavaScript’s Set object and manipulate arrays.
What is a Set object?
Set objects allow you to add, remove, and search elements in an array.
You can also choose not to add duplicate elements.
How to manipulate arrays using Set objects
The Set object is a data structure introduced after ES2015 that can handle a set of unique elements .
You can add elements to an array using the Set object. Since you cannot add duplicate elements when adding elements to a Set object, you can guarantee that there are no duplicate elements in the array.
- Use the add method to add elements to the Set object .
- To remove an element from a Set object, use the delete method.
- Use the has method to search for elements within a Set object .
- Use the clear method to remove all elements of a Set object .
Below is a sample code to add an element using a Set object using the add method.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
console.log(set); // Set {1, 2, 3}
Below is a sample code to delete an element from a Set object using the delete method.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.delete(2);
console.log(set); // Set {1, 3}
Below is a sample code that uses the has method to search for an element in a Set object.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
console.log(set.has(2)); // true
Extract all values of Set using forEach
There are several ways to retrieve all the values of a Set object, but one way is to use the forEach method. The forEach method can process all elements in a Set object one by one.
Below is a sample code that uses the forEach method to retrieve all values in a Set object.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.forEach(value => {
console.log(value);
});
// 1
// 2
// 3
Alternatively, you can create an array from a Set object using the Array.from method. All values in a Set object converted to an array can be retrieved using the for statement or array methods.
Below is a sample code that uses the Array.from method to create an array from a Set object and extracts all the values in that array.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
let array = Array.from(set);
for (let value of array) {
console.log(value);
}
// 1
// 2
// 3
Summary of this article
We explained how to use the Set object.
- A Set object is a data structure that can handle a set of unique elements.
- Use the “add” method to add elements.
- Use the “delete” method to delete an element.
- Use the “has” method to search for an element.
- Use the clear method to remove all elements .
- To retrieve all values of a Set object, use the forEach method or Array.from method.
By using Set objects, it is now easy to manipulate array elements without worrying about duplicates!
If you can use them differently from regular arrays depending on the purpose, you will be able to write easier-to-read code.
Comments