Created
November 8, 2016 09:34
-
-
Save tandat2209/4c2941b79f49fbdbf980658eb6d3c8b0 to your computer and use it in GitHub Desktop.
Group Anagrams
This file contains hidden or 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 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