# Using Sets in JavaScript

If you’ve ever written any Python, you’ve likely come across sets. They’re really useful for creating a data structure where every element is ‘distinct’ (i.e. it has no duplicates).

If you want a mathematical definition, from Wolfram Math:

A set is a finite or infinite collection of objects in which order has no significance, and multiplicity is generally also ignored (unlike a list).

So order isn’t important, and you can’t have duplicates.

### Using Sets in JavaScript

ES6 introduced sets to JavaScript:

Now we have a set! We can use the in-built methods to add, delete, search etc. These will seem familiar to array methods.

A JavaScript set returns an Iterable - that is something you can iterate over! And so to loop, you can use `forEach`

, or `let X of Set`

:

and:

Iterators are handy, and a future blog post will cover iterators and generators!

### Be Careful with Equality!

In a set, order is unimportant. The contents of a set are said to be the same if they contain the same elements, but they don’t need to be in the same order. Think of a set as as box that contains a load of ‘things’. Two boxes either contain the same things, or they don’t.

In Python, this equality is observed. For example:

However, in JavaScript it is **not**:

JavaScript doesn’t compare equality of sets in the true sense, it compares whether they are the same object (which they aren’t, in the example above).

### Bonus: Simply convert an array into a array without duplicates

As a bonus, we can combine the Set() object with ES6’s spread operator (`...`

), and re-populate an array with our new set, complete with only the unique values of our original array. No need for reducers or filters!

## Wrap Up

JS sets are useful little utilities. They aren’t as rigourously implemented as Python sets (see the issues with comparison), but for tasks such as removing duplicates they can definitely become part of your arsenal.