Algorithm


  1. Input:

    • Accept a list of words as input.
  2. Tokenization:

    • Tokenize the input string into individual words. You can use a regular expression or the split method to achieve this.
  3. Sorting:

    • Use the sort method to sort the array of words. The sort method sorts elements of an array in place and by default, it sorts strings in alphabetical order.
  4. Output:

    • Display or return the sorted list of words.

 

Code Examples

#1 Code Example- Sort Words in Alphabetical Order

Code - Javascript Programming

// 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);
}
Copy The Code & Try With Live Editor

Output

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

#2 Code Example with Javascript Programming

Code - Javascript Programming

// 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);
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a sentence: i am learning javascript
The sorted words are:
am
i
javascript
learning
Advertisements

Demonstration


JavaScript Programing Example to Sort Words in Alphabetical Order-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way