Signup/Sign In
PUBLISHED ON: FEBRUARY 15, 2023

JavaScript Program to Sort words in Alphabetical order

Sorting words alphabetically is a common programming problem. To sort words alphabetically in JavaScript, you can use built-in methods or create custom functions. Sorting strings can help you organize data and present it in a more readable format. In this program, we will look at various methods for sorting words in alphabetical order using JavaScript.

This program will teach you how to sort words in alphabetical order using JavaScript, whether you are a beginner or an experienced programmer. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

Approach

The user is asked to enter a sentence for which we want the words to be in sorted order.

  • The split() function primarily divides the sentence into array characters.
  • The array elements are sorted using the sort() method. This function will sort the elements/characters in alphabetically sorted order.
  • Finally, we will have a for...of loop that will be used to iterate over the elements and print them accordingly.

Program to Sort words in Alphabetical order

// JS Program to sort words in alphabetical order

let sentence = prompt('Enter a sentence:');

// converting to an array
let words = sentence.split(' ');

// sort the array elements
words.sort();

console.log('The sorted words are:');

for (let element of words) 
  console.log(element);


Enter a sentence: i am learning javascript
The sorted words are:
am
i
javascript
learning

Special Note

The Upper-Case characters are placed in higher order with respect to lower-case characters.

For Example:

I am learning JavaScript 


I
JavaScript
am
learning

Upper characters like I, and Javascript are presented before ' am '. Because I and J are uppercase characters and in the sort method, upper case characters are given preference over the lower case characters.

Conclusion

Finally, sorting words alphabetically is a useful problem to solve in programming, and JavaScript provides several approaches to accomplishing this task. In this program, we looked at various JavaScript methods for sorting words alphabetically. To achieve our goal, we used built-in methods like sort() as well as custom functions built with loops. You may prefer one method over another, depending on the needs of your project and your personal coding style.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.