rjhilgefort
9/16/2019 - 11:24 PM

groupAnagrams

// 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))