Member-only story

JavaScript Algorithm: Alphabet Soup

Max N
2 min readMar 14, 2020

--

For today’s algorithm, we are going to write a function called AlphabetSoup that will take in one string, str, as input.

You are given a string; the goal of the function is to return the strings with the letters in alphabetical order. Assume no numbers and punctuations are in the input. Here is an example:

let str = "happy";

Our string input is "happy" and if we sort the characters in alphabetical order the function will return, "ahppy".

Let’s turn this problem into code. We create a variable called sortStr.

let sortedStr = str.toLowerCase().split("").sort().join("");

Since we are going to return the string with the characters in alphabetical order, we can use the sort() method. But before we do that, we will lowercase the string. This is in case our input string contains an upper case letter. If we try to sort a string with a combination of upper case and lower case letters, the sort method will sort the capitalized characters before the lower case letters.

Sorting the string “Happy” will return “Happy” but if we lowercase all the letters, the sort method will return “ahppy”. The sort sorts characters according to its Unicode value. If you look at an ASCII table, upper case letters have a lower Unicode value than lower caser…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

Responses (1)