Skip to content

Instantly share code, notes, and snippets.

@woonketwong
Created December 30, 2013 18:33
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 woonketwong/8185932 to your computer and use it in GitHub Desktop.
Save woonketwong/8185932 to your computer and use it in GitHub Desktop.
A method to sort an array of strings so that all the anagrams next to each other.
var sortAndGroupAnagram = function(array){
var result = {};
var sortedResult = [];
var currentKey;
var allKey;
for (var i = 0; i < array.length; i++){
currentKey = array[i].split('').sort().join('');
if ( result.hasOwnProperty(currentKey) ){
result[currentKey].push(array[i]);
} else {
result[currentKey] = [ array[i] ];
}
}
allKey = Object.keys(result);
allKey.sort();
for ( var j = 0; j < allKey.length; j++){
sortedResult = sortedResult.concat(result[allKey[j]]);
}
return sortedResult;
}
//var array = ["apple", "ybab", "zibra", "pplea", "arbiz", "baby", "lppae"];
//var temp = sortAndGroupAnagram(array);
//console.log(temp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment