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





Services
  • SEO
  • Online Advertising
  • Online Ordering For Restaurants
  • Data Analytics

  • External Resources 4 Developers
  • CSS Tricks
  • MDN

  • Dash-Intel.com is a Power BI and Tableau resource site around data visualizations and building business dashboards.

    Data Analytics consultants in Edmonton, Alberta specializing in Tableau and marketing analytics

    Copyright 2020 Dash-Intel.com Terms / All rights reserved.