Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Last active October 20, 2020 19:17
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 Gerst20051/67eebb0f15d8f8b39e9c19f8e7f31f67 to your computer and use it in GitHub Desktop.
Save Gerst20051/67eebb0f15d8f8b39e9c19f8e7f31f67 to your computer and use it in GitHub Desktop.
Group Anagrams
function groupAnagrams(listOfStrings) {
return listOfStrings.reduce((groups, string) => {
for (let i = 0; i < groups.length; i++) {
if (isAnagram(groups[i][0], string)) {
groups[i].push(string);
return groups;
}
}
groups.push([string]);
return groups;
}, []);
}
function isAnagram(firstString, secondString) {
const firstCharacters = firstString.split('');
const secondCharacters = secondString.split('');
for (let i = 0; i < secondCharacters.length; i++) {
const characterIndex = firstCharacters.indexOf(secondCharacters[i]);
if (characterIndex === -1) return false;
firstCharacters.splice(characterIndex, 1);
}
if (firstCharacters.length) return false;
return true;
}
console.log(groupAnagrams(['catt', 'cat', 'bat', 'cinema', 'tab', 'tac', 'iceman', 'act']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment