Skip to content

Instantly share code, notes, and snippets.

@jasonseminara
Created January 15, 2019 17:11
Show Gist options
  • Save jasonseminara/31d9b11a922265783c6f077adfecfe39 to your computer and use it in GitHub Desktop.
Save jasonseminara/31d9b11a922265783c6f077adfecfe39 to your computer and use it in GitHub Desktop.
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