Skip to content

Instantly share code, notes, and snippets.

@Demwunz
Last active January 13, 2020 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Demwunz/4ad90caa167001985f43ef5f8f9ba444 to your computer and use it in GitHub Desktop.
Save Demwunz/4ad90caa167001985f43ef5f8f9ba444 to your computer and use it in GitHub Desktop.
Remove Duplicates from Array - JavaScript
/* copied from an email */
/*The first piece we need is the Set object. This is one of the new objects available in recent versions of JavaScript.
It’s something we don’t typically use much. The Set object is very cool because it’s a collection a little like an array,
but it ONLY allows unique items. If we try to add a duplicate item to its collection, then it just silently doesn’t add the item.
So if we give it five 3’s then it will only have 1 item in it, a single 3.
The Set object’s constructor will take in any iterable object, which includes arrays. So we can give a Set an array,
and it’ll load in the elements and any duplicates won’t get loaded. We do that like this:*/
let arrayWithDups = [1,1,1,2,3,4,4,5,5,6]
let uniqueSet = new Set(arrayWithDups);
/*Now that we have a Set with the unique items we want, we just need to turn that back into an array.
Here the Array.from method comes to the rescue.
This static method will take any array-like or iterable object, and create a new array from it.
So when we pass in our Set to Array.from, it’ll create a new array with the elements of the Set. */
let arrayWithoutDups = Array.from(uniqueSet);
/*So combining these, in a single line of code we can remove duplicates from an Array with nice, concise code. */
let arrayWithoutDups = Array.from(new Set(arrayWithDups));
// [1,2,3,4,5,6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment