JavaScript Program to Sort Words in Alphabetical Order

In this example, you will learn to write a JavaScript program that sorts words in a string in an alphabetical order.

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example: Sort Words in Alphabetical Order

// program to sort words in alphabetical order

// take input
const string = prompt('Enter a sentence: ');

// converting to an array
const words = string.split(' ');

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

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

for (const element of words) {
  console.log(element);
}

Output

Enter a sentence: I am learning JavaScript
The sorted words are:
I
JavaScript
am
learning

In the above example, the user is prompted to enter a sentence.

  • The sentence is divided into array elements (individual words) using the split(' ') method. The split(' ') method splits the string at whitespaces.
    const words = string.split(' '); // ["I", "am", "learning", "JavaScript"]
  • The elements of an array are sorted using the sort() method. The sort() method sorts the strings in alphabetical and ascending order.
    words.sort(); // ["I", "JavaScript", "am", "learning"]
  • The for...of loop is used to iterate over the array elements and display them.

Note: Instead of displaying from the array values, you can also convert the array elements back to the string and display the values as a string using join() method.

words.join(' '); // I JavaScript am learning