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. Thesplit(' ')
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. Thesort()
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