Skip to content

Instantly share code, notes, and snippets.

@meduzen
Last active March 10, 2021 16:00
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 meduzen/dab25dc692c2f9339be4e146526b6fbc to your computer and use it in GitHub Desktop.
Save meduzen/dab25dc692c2f9339be4e146526b6fbc to your computer and use it in GitHub Desktop.
JavaScript Set explained
// Embedded in https://twitter.com/meduzen/status/1369679118992871428
// OMG, lot of duplicated entries!
const stepsNames = [
"step-basic",
"step-basic",
"step-basic",
"step-specification",
"step-specification",
"step-specification",
"step-specification",
"step-specification",
"step-title-description",
"step-contact-information",
"step-pricing",
"step-payment",
"step-confirmation"
]
// Let’s remove them in two steps!
// 1. With a Set, we can have a collection of unique values:
let uniqueStepsNames = new Set(stepsNames)
// Duplicates are now gone, but Set is an object, not an array:
// { 0: "step-basic", 1: "step-specification"… }
// 2. Using the spread syntax, we turn the object into an array.
uniqueStepsNames = [...uniqueStepsNames]
// This 👆 can be read:
// “Creates an ARRAY [] that will receive ALL INNER VALUES OF ...uniqueStepsNames.”
// `uniqueStepsNames` is now an array:
// ["step-basic", "step-specification"…]
// Or, alternatively, in 1 step instead of 2:
const uniqueStepsNames = [...new Set(stepsNames)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment