Skip to content

Instantly share code, notes, and snippets.

@yalovek
Last active October 23, 2016 15:24
Show Gist options
  • Save yalovek/e4babe58431f0a861e53dc69924d62dc to your computer and use it in GitHub Desktop.
Save yalovek/e4babe58431f0a861e53dc69924d62dc to your computer and use it in GitHub Desktop.
Function for checking array of words for anagrams
/**
* 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