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.
Now we have a set! We can use the in-built methods to add, delete, search etc. These will seem familiar to array methods.
let X of Set:
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:
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!
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.