Created
September 16, 2019 23:24
-
-
Save rjhilgefort/89f3f4aef40ceac2a9f9a56b2fd4ef10 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
// 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