Bryan Lee

Removing duplicates from an array in ES6 Javascript

· JavaScript

ES6 introduces a new type of Set object that stores unique values. This is very useful if you want to get only unique values from an array, similar to Ruby's uniq method.

let originalArray = ['a', 'b', 'c', 'a', 'a', 'd', 'e']
let uniqueArray = new Set(originalArray) // ['a', 'b', 'c', 'd', 'e']

Sets are similar to Arrays and you can also use methods like add. This is also useful for adding new entries and removing duplicates. Continuing from the example above:

uniqueArray.add('a') // ['a', 'b', 'c', 'd', 'e']
uniqueArray.add('f') // ['a', 'b', 'c', 'd', 'e', 'f']

Sets take iterable objects as arguments, so you can also pass in a string to get the unique alphabets in a string:

new Set("hello") // Set ['h', 'e', 'l', 'o']