Ditching Dupes with a Set
Tags: javascript
Published: 2020-02-29 22:26:10

A JavaScript Set object is a useful data structure when dealing with duplicate data. Introduced with ES6, a Set is a collection that stores unique values of any type, whether primitive types or object references. Say, for example, you want to de-dupe an Array and know there must be a better way than iterating through the Array and push non-duplicate values into a new Array. A Set can help with you that!

###Unique Values

![simpson's gif of duplicates](https://media.giphy.com/media/xT5LMDhY4k2HEAhD3O/giphy.gif "Simpsons Gif")

**A value in a Set can only occur once and is unique in the Set’s collection.** As each value in the Set has to be unique, the value equality will be checked.

Something to keep in mind is that if two objects have the same value(s) but do not share the same reference they will not be considered equal.

```javascript
const arr1 = ['Simpsons'];
const arr2 = ['Simpsons'];
arr1 === arr2; // false
arr1[0] === arr2[0]; // true
const set = new Set();
set.add(arr1); // Set { ['Simpsons'] }
set.add(arr2); // Set { ['Simpsons'], ['Simpsons'] }
set.add('Simpsons'); 
set; // Set { ['Simpsons'], ['Simpsons'], 'Simpsons' } 
```

###Getting Started

Below is how to initialize a new Set:
```javascript
const mySet = new Set(); // Set {}
```

###Set Properties and Methods

A useful Set method is `add()` which adds a new item to the Set and returns the Set object. `size()` is a Set property that returns the number of items in the Set:

```javascript
mySet.add('Homer'); // Set {'Homer'}
mySet.add('Lisa'); // Set {'Homer', 'Lisa'}
mySet.add('Bart'); // Set {'Homer', 'Lisa', 'Bart'}
mySet.size; // 3
```

You can also initialize a Set with an array of values.
```javascript
const mySet = new Set(['Homer', 'Lisa', 'Bart', 'Homer']); 
newSet; // Set {'Homer', 'Lisa', 'Bart'}
```

Other useful methods include `has()` which returns a boolean indicating whether the passed in element is present in the Set object or not.

```javascript
mySet.has('Homer'); //true
mySet.has('Moe'); //false
```

`delete()` deletes the element passed in and returns the value that `has()` would have returned (so a good rule of thumb is seeing `true` for a successful deletion). Using `has()` to check that since deleted value will result in a false.

```javascript
mySet.delete('Bart'); // true
mySet; // Set {'Homer', 'Lisa'};
mySet.has('Bart'); // false
mySet.size // 2
```

And if you need to remove all of the elements in your Set, you can use `clear()`.

```javascript
mySet.clear();
mySet; // Set {}
```

You can iterate over items in the Set using either `for...of` or `forEach()`. **Iteration over a Set is always in insertion order**, so while these collections are not unordered there is no index kept and we cannot reorder elements once they're set in the Set.

```javascript
//using for...of
for (const val of mySet) console.log(val); 

//using forEach
mySet.forEach(val => console.log(val));
```

And now to finally circle back after all of this buildup from my introductory paragraph about wanting to use a Set to de-dupe an array, it is as simple as the following utilizing the spread operator:

```javascript
const numbers = [1, 3, 5, 5, 7, 9];
const numSet = [...new Set(numbers)];
numSet; // [ 1, 3, 5, 7, 9 ]
```

Set objects will not be the best data structure for every situation but they appear to be a useful supplement to Arrays and Objects, especially when working with duplicate data.


Resources
[Sets - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
[Understanding Map and Set in JavaScript](https://www.taniarascia.com/understanding-map-and-set-javascript/)