+ 1
Write a JavaScript function that returns a .4 passed string with letters in alphabetical 'order. Example string : 'webmaster 'Ex
Write a JavaScript function that returns a .4 passed string with letters in alphabetical 'order. Example string : 'webmaster 'Expected Output : 'abeemrstw Assume punctuation and numbers symbols .are not included in the passed string
2 Antworten
+ 3
function sorter(str) {
return str.split("").sort().join("")
}
+ 1
Just implement a sorting algorithm that sorts the ASCII codes of the characters in ascending order (because the ASCII value of 'A' is 65 and the one of 'B' is 66).
I published the code, so you can run it directly here on SoloLearn: https://code.sololearn.com/WXD4DwMWjyZd/
But if you prefer just the code here it is:
alert(sort("webmaster"));
function sort(word){
var chars = []
// convert to integer array
for(var i = 0; i < word.length; i++){
chars.push(word.charCodeAt(i));
}
//now just sort the array
var sorted = []
for(var i = 0; i < word.length; i++){
var lowest = getLowestInt(chars); // get lowest element: (A = 65) < (B = 66)
sorted.push(lowest);
chars.splice(chars.indexOf(lowest), 1) // remove from array containing remaining chars
}
// join to string
var sortedString = "";
for(var i = 0; i < sorted.length; i++){
sortedString += String.fromCharCode(sorted[i]);
}
return sortedString;
}
function getLowestInt(array){
var lowest = 1000; // no ascii code is higher than this
for(var i = 0; i < array.length; i++){
if(array[i] < lowest){
lowest = array[i];
}
}
return lowest;
}