Last active
October 23, 2016 15:24
-
-
Save yalovek/e4babe58431f0a861e53dc69924d62dc to your computer and use it in GitHub Desktop.
Function for checking array of words for anagrams
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
/** | |
* Function for checking array of words for anagrams | |
* @param {Array} words Array of words | |
* @return {Array} Array of arrays with anagram words | |
*/ | |
const anagram = words => words.reduce((result, word) => { | |
if (!result[word.length]) { | |
result[word.length] = [word]; | |
} | |
else { | |
result[word.length].push(word); | |
} | |
return result; | |
}, []) | |
.map(words => words.reduce((result, word) => { | |
var sorted = word.split('').sort().join(''); | |
if (!result[sorted]) { | |
result[sorted] = [word]; | |
} | |
else { | |
result[sorted].push(word); | |
} | |
return result; | |
}, {})) | |
.map(words => Object.keys(words).map(key => words[key])) | |
.reduce((result, words) => { | |
words.forEach(word => result.push(word)); | |
return result; | |
}, []) | |
.filter(words => words.length > 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment