Created
November 11, 2020 21:26
-
-
Save DoctorDerek/e7fcbe36b2b8d514146870fe43cdb255 to your computer and use it in GitHub Desktop.
Finding Unique Strings using a JavaScript Object
This file contains hidden or 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
const myStrings = ["👌", "👌", "👌", "🐱👤", "🐱👤", "🐱🚀", "🐱🚀"] | |
const myUniqueStrings = [] | |
const myStringObject = {} // Used to check for uniqueness | |
for (const string of myStrings) { | |
// Object keys that aren't yet set are undefined, | |
// and undefined is a falsy value in JavaScript. | |
if (!myStringObject[string]) { | |
myUniqueStrings.push(string) | |
myStringObject[string] = true | |
} | |
} | |
// JavaScript objects must have unique keys (properties), | |
// so this method finds the unique strings in an array. | |
console.log(myUniqueStrings) | |
// Output: Array(3) [ "👌", "🐱👤", "🐱🚀" ] | |
// Alternatively you can get the keys with Object.keys() | |
console.log(Array.from(Object.keys(myStringObject))) | |
// Output: Array(3) [ "👌", "🐱👤", "🐱🚀" ] | |
// Equivalent to using the spread operator: | |
console.log([...Object.keys(myStringObject)]) | |
// Output: Array(3) [ "👌", "🐱👤", "🐱🚀" ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment