Created
December 30, 2013 18:33
-
-
Save jack-wong-build/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.
This file contains 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
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