Skip to content

Instantly share code, notes, and snippets.

@rjhilgefort
Created September 16, 2019 23:24
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 rjhilgefort/89f3f4aef40ceac2a9f9a56b2fd4ef10 to your computer and use it in GitHub Desktop.
Save rjhilgefort/89f3f4aef40ceac2a9f9a56b2fd4ef10 to your computer and use it in GitHub Desktop.
// input array of words - ['tea', 'eat', 'ate', 'leap', 'peak', 'foo', 'bar']
// output - [ ['eat', 'ate', 'tea'], ['foo'], {'bar'}, {'leap', 'peal'}]
const foo = (words) => {
const wordsGrouped = words.reduce(
(acc, word) => {
const sortedWord = word.split('').sort().join('')
// Make sure we have an entry for this sorted word
if (!acc[sortedWord]) {
acc[sortedWord] = []
}
acc[sortedWord].push(word)
return acc
},
// { [string: sortedKey]: [word] }
{},
words
)
return Object.entries(wordsGrouped).map(([_key, val]) => val)
}
const test1 = ['tea', 'eat', 'ate', 'leap', 'peal', 'foo', 'bar']
console.log(foo(test1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment