Last active
October 20, 2020 19:17
-
-
Save Gerst20051/67eebb0f15d8f8b39e9c19f8e7f31f67 to your computer and use it in GitHub Desktop.
Group 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 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