Unique Values With Set

Open the project folder

In our starter files, open the index.html page from this lessons folder:

02.Arrays-In-More-Depth > 09.Unique-values-with-set

Creating a Set

Our starter files have this array of categories:

let categories = [
  'bags',
  'shoes',
  'shirts',
  'ties',
  'jackets',
  'hats',
  'bags',
];

And if you look closely, it has the bags value twice. Arrays will accept any values we push to it, even if they are duplicate. A way we can avoid this if needed is to use Set.

Even though is looks like one, Set is not an array, instead it is what is called a collection, and it can store both primitive and object values.

Sets can be created from scratch, or we can convert our array like this:

let categories = [
  'bags',
  'shoes',
  'shirts',
  'ties',
  'jackets',
  'hats',
  'bags',
];
let uniqueCategories = new Set(categories);
console.log(uniqueCategories); // 0: "bags" 1: "shoes" 2: "shirts" 3: "ties" 4: "jackets" 5: "hats"

The uniqueCategories variable will now be a collection of unique values.

Built in methods

Set has some built in methods we can use to modify the collection. To add a new value, we have add:

let uniqueCategories = new Set(categories);
uniqueCategories.add('jeans');

Duplicated categories will not be accepted, even with this method.

We can remove single items with the delete method:  

let uniqueCategories = new Set(categories);
uniqueCategories.delete('ties');

Or we can remove all items with clear:

let uniqueCategories = new Set(categories);
uniqueCategories.clear();

We can check if a certain value is included in the Set with the has method, since this returns true or false, it also needs to be stored in a variable:

let uniqueCategories = new Set(categories);
const hasShoes = uniqueCategories.has('shoes');
console.log(hasShoes); // true

The size property

Just like arrays have the length property, set has the same thing but it is called size:

let uniqueCategories = new Set(categories);
console.log(uniqueCategories.size); // 6

When using arrays, we can also use array methods such as filter to remove duplicates, but this is a little more complex than using Set.

So, if you need to have a collection of unique values, Set is a great way to achieve this.