Skip to content

Instantly share code, notes, and snippets.

@muhsalaa
Last active May 18, 2020 04:55
Show Gist options
  • Save muhsalaa/b78453b51076e28b93b43343565238e8 to your computer and use it in GitHub Desktop.
Save muhsalaa/b78453b51076e28b93b43343565238e8 to your computer and use it in GitHub Desktop.
Interview question about group anagram answer in javascript
// input: ['tea','you', 'eat', 'ate', 'ouy', 'hard']
// output: [
// ['tea', 'eat', 'ate'],
// ['you', 'ouy'],
// ['hard']
// ]
function groupAnagram(arr) {
// we will put result here
const output = {};
// normalize word to get the similarity among all word
const normalizeWord = (word) => word.split('').sort().join('');
// iterate the array input
arr.forEach((x) => {
// if key exist in output
output[normalizedWord(x)]
// push the value
? output[normalizedWord(x)].push(x)
// else give a new key and value to output
: (output[normalizedWord(x)] = [x]);
});
// finally, get all output values with Object.values() method
console.log(Object.values(output));
}
// ref: https://medium.com/javascript-in-plain-english/algorithms-101-group-anagrams-in-javascript-b3e3c10d211e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment