Created
January 15, 2019 17:11
-
-
Save jasonseminara/31d9b11a922265783c6f077adfecfe39 to your computer and use it in GitHub Desktop.
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
const colors = 'red orange red yellow green blue yellow indigo violet red indigo orange green blue'; | |
const colorsMapped = colors.split(' ').reduce((set, item, i) => { | |
if (item in set) return set; | |
// if the item isn't in the set, put it in and record its position | |
// don't do any mutations! | |
return { | |
...set, | |
[item]: i, | |
} | |
}, {}); | |
// Object.entries converts our unsortable object into an array we can sort | |
// each item will be [color, order] | |
const solution = Object.entries(colorsMapped) | |
/* destructure the args so each item will be [color, order]; sort by order */ | |
.sort(([ ,orderA], [ ,orderB]) => orderA - orderB) | |
/* sort doesn't let us modify the array, so let's map over and grab only what we need */ | |
.map(([colorName]) => colorName) | |
/* convert to a string */ | |
.join(' '); | |
console.log(solution); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment