Javascript Sets

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.

Creating a new set

We can create a new set in javascript using the following syntax

   
                         let groceryCart = new Set(); //create a new set called groceryCart
                       

Adding items to the set

We add new items using the `add` method in javascript

   
                      groceryCart.add('coffee');
                       

Adding multiple items to the set

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

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.
                       

Remove items from a set

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');
                       

Check to see if items are in the set

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'));
                       

Removing all elements in thet set

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();
                       

Converting a set into an array

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];
                       


Dash-Intel is a Power BI and Tableau resource site for data visualization and building BI dashboards.

Data Analyst & Consultant

Copyright 2015-2023 Dash-Intel.com Terms