Skip to content

Instantly share code, notes, and snippets.

@mskims
Created May 19, 2017 02:20
Show Gist options
  • Select an option

  • Save mskims/1239173c1d1f3ea98502ed307a234b77 to your computer and use it in GitHub Desktop.

Select an option

Save mskims/1239173c1d1f3ea98502ed307a234b77 to your computer and use it in GitHub Desktop.
/**
* input: ["leary", "abc", "early", "relay", "rayle", "layer", "cba"]
* output: [["leary", "early", "relay", "rayle", "layer"], ["abc", "cba"]]
*/
const inputs = ["leary", "abc", "early", "relay", "rayle", "layer", "cba"];
const haystack = {};
inputs.forEach(input=>{
const sortedInput = input.split("").sort().join("");
if(haystack.hasOwnProperty(sortedInput)){
haystack[sortedInput].push(input);
}else{
haystack[sortedInput] = [input];
}
});
const anagrams = [];
for (let key in haystack){
if(haystack[key].length > 1){
anagrams.push(haystack[key]);
}
}
console.log(anagrams);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment