Created
January 3, 2019 14:53
-
-
Save overra/f4e489be16acab2db76460e8f041f709 to your computer and use it in GitHub Desktop.
Tip: Get the unique values of an array in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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