Monday, July 19, 2021

Junior Developer Central JS Practice Exercise - 21

 
Question: 

Write a Javascript function that returns a passed string with letters in alphabetical order. 

Example String:           'javascript' 
Example Output:          'aacijprstv'




Answer: 

function alphaStr (str) {

return str.split('').sort().join('')

}          




> we declare a function 'alphaStr' 
> it has one parameter 'str' 
> we use the split ('') method on the string 'str' to split all the characters in an array
> we then use the sort() method to sort the characters in alphabetical order
> we then use the join('') method to create a string by concatenating all the sorted elements of the array created 
> we return this line of code to get our alphabetically sorted string

No comments:

Post a Comment