Skip to content

Instantly share code, notes, and snippets.

@overra
Created January 3, 2019 14:53
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 overra/f4e489be16acab2db76460e8f041f709 to your computer and use it in GitHub Desktop.
Save overra/f4e489be16acab2db76460e8f041f709 to your computer and use it in GitHub Desktop.
Tip: Get the unique values of an array in JavaScript.
// borrowed from Addy Osmani
// Way 1: new Set()
const uniqueArray = arr => [...new Set(arr)];
uniqueArray(['Dan', 'Sarah', 'Sophie‘, ’Sarah']);
// ["Dan", "Sarah", "Sophie"]
// Way 2: Array.from() and new Set()
const uniqueArray2 = arr => Array.from(new Set(arr));
// Way 3: using Array#filter and Set() - may be faster
const seen = new Set();
const uniqueArray3 = arr => arr.filter(x => {
if (seen.has(x)) return false; seen.add(x);
return true;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment