Skip to content

Instantly share code, notes, and snippets.

@tandat2209
Created November 8, 2016 09:34
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 tandat2209/4c2941b79f49fbdbf980658eb6d3c8b0 to your computer and use it in GitHub Desktop.
Save tandat2209/4c2941b79f49fbdbf980658eb6d3c8b0 to your computer and use it in GitHub Desktop.
Group Anagrams
function group(arr){
let result = [];
let j=0;
let tmp = arr;
while(tmp.length > 0){
let cmp = tmp[0];
result[j] = [];
for(let i=0; i<tmp.length;i++){
if(isAnagram(cmp, tmp[i])){
result[j].push(tmp[i]);
tmp.splice(i,1);
}
}
j++;
}
return result.filter(function(i){
return i.length > 1
});
}
function isAnagram(a, b){
let sortedA = a.split('').sort().join('');
let sortedB = b.split('').sort().join('');
return sortedA == sortedB;
}
let result = group(["bat", "tar", "xyz", "tab", "tar", "abt"]);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment