Javascript sets allow you to store a unique list of items. Sets cannot have duplicate values and will ignore any duplicate values being put into the set. The basic properties of sets are outlined below.
We can create a new set in javascript using the following syntax
let groceryCart = new Set(); //create a new set called groceryCart
We add new items using the `add` method in javascript
groceryCart.add('coffee');
One way of adding multiple items to the set is using a loop
const groceryList = ['apples','oranges','bananas','coffee','tea','coffee','coffee'];
groceryList.forEach(item => {
groceryCart.add(item); // add each item in the groceryList to the groceryCart set
})
The size property of sets lets you find the number of items in thet set, similar to how the length property works for arrays
// use the `size` method the check the length of the shopping cart
console.log(groceryCart.size); // will count distinct values only.
The delete property of sets lets you remove items from the set.
// use the `delete` method to remove coffee in the shopping cart
groceryCart.delete('coffee');
The `has` property of sets lets you check if items are in the set.
// use the has method to check if coffee is in the shopping cart.
console.log(groceryCart.has('coffee'));
The clear property of sets lets you check if items are in the set.
// use the `clear` method to remove all items in the shopping cart.
groceryCart.clear();
If you want to convert a set into an array you can use destructring
// convert groceryCart set into an array using destructuring.
const groceryCartToArray = [...groceryCart];