Last active
March 10, 2021 16:00
-
-
Save meduzen/dab25dc692c2f9339be4e146526b6fbc to your computer and use it in GitHub Desktop.
JavaScript Set explained
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
// 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