Skip to content

Instantly share code, notes, and snippets.

@dvmonroe
Created November 5, 2015 23:39
Show Gist options
  • Save dvmonroe/19ca02b034bc5f63bd26 to your computer and use it in GitHub Desktop.
Save dvmonroe/19ca02b034bc5f63bd26 to your computer and use it in GitHub Desktop.
js string sorting
var testString = "Partner World Dog Cat Xyelephone New. shorts apple summer a tiny"
function sortDescending(a, b){
if (a > b) return -1
if (a < b) return 1
else return 0
}
function sortArrayAndStringify(array, sortComparator){
var o = "";
array.sort(sortComparator)
array.forEach(function(val){ o += val + " " })
return o // return a sorted string
}
function splitLowerCaseAndSort(string){
var arr = string.split(" "),
newArr = [];
for (var i = 0; i <= arr.length - 1; i++){
var value = arr[i]
if (value[0] == value[0].toLowerCase()){
newArr.push(value)
}
}
return sortArrayAndStringify(newArr)
}
function splitUpperCaseAndSort(string){
var arr = string.split(" "),
newArr = [];
for (var i = 0; i <= arr.length - 1; i++){
var value = arr[i]
if (value[0] == value[0].toUpperCase()){
newArr.push(value)
}
}
return sortArrayAndStringify(newArr, sortDescending)
}
function runTest(string){
var desiredString = [splitLowerCaseAndSort(string), splitUpperCaseAndSort(string)].join("").trim()
return desiredString.replace(/\./g,' ') // replace period in string
}
runTest(testString)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment