JavaScript Program to Sort Words in Alphabetical Order
Last Updated :
30 Aug, 2024
Sorting words in alphabetical order involves arranging them based on the standard sequence of letters in the alphabet. This process helps in organizing data, making searches efficient, and presenting information in a clear and systematic manner.
Methods to sort words
We will explore every approach for sorting words in Alphabetical Order, along with understanding their basic implementations.
Using the Array sort() method
The sort()
method sorts all the elements of the array and returns the sorted array. By default, the sort()
method sorts the elements in lexicographic (alphabetical) order. We can simply pass the array of words to the sort()
method to sort themconst sortedWords = wordsArray.sort(); alphabetically.
Syntax:
arr.sort(compareFunction);
Example: In this example, we will see the use of the sort() Method.
JavaScript
const words = [
"JavaScript",
"Program",
"to",
"Sort",
"Words",
"in",
"Alphabetical",
"Order",
];
// Sorting the input array using array.sort
const sortedWords = words.sort();
//Getting the sorter array output
console.log(sortedWords);
Output[
'Alphabetical',
'JavaScript',
'Order',
'Program',
'Sort',
'Words',
'in',
'to'
]
The localeCompare()
the method compares two strings and returns a number indicating their relative order. We can use the localeCompare()
the method as a custom sorting function in conjunction with the sort()
method.
Syntax:
const sortedWords = wordsArray.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
Example: In this example, we will see the use of the localeCompare() Method.
JavaScript
const words = [
"JavaScript",
"Program",
"to",
"Sort",
"Words",
"in",
"Alphabetical",
"Order",
];
// Sorting array using localeCompare
const sortedWords = words.sort((a, b) =>
a.localeCompare(b, undefined, { sensitivity: "base" })
);
// Show the sorted array output
console.log(sortedWords);
Output[
'Alphabetical',
'in',
'JavaScript',
'Order',
'Program',
'Sort',
'to',
'Words'
]
Implementing a custom sorting algorithm
Implementing a sorting algorithm manually, we can use approaches like bubble sort, insertion sort, or merge sort. These algorithms compare pairs of words and swap them based on their order until the entire list is sorted.
Syntax:
function bubbleSort(wordsArray) { // ...implementation of bubble sort }
Example: In this example, we will see the use of a custom bubble sort function.
JavaScript
// Implementing bubble sort function
function bubbleSort(wordsArray) {
// Getting size of array
const length = wordsArray.length;
for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (
wordsArray[j]
.localeCompare(wordsArray[j + 1], undefined, {
sensitivity: "base",
}) > 0
) {
// Swaping word in the array
const temp = wordsArray[j];
wordsArray[j] = wordsArray[j + 1];
wordsArray[j + 1] = temp;
}
}
}
return wordsArray;
}
const words = [
"JavaScript",
"Program",
"to",
"Sort",
"Words",
"in",
"Alphabetical",
"Order",
];
const sortedWords = bubbleSort(words);
// Getting the sorted array output
console.log(sortedWords);
Output[
'Alphabetical',
'in',
'JavaScript',
'Order',
'Program',
'Sort',
'to',
'Words'
]
Using the Intl.Collator object
The Intl.Collator object is built specifically for language-sensitive string comparison. It provides options for specifying locale-specific sorting, handling diacritics, and sensitivity to case. By default, it sorts strings in the language-sensitive order.
Syntax:
const collator = new Intl.Collator(undefined, { sensitivity: 'base' });
const sortedWords = wordsArray.sort(collator.compare);
Example: In this example, we’ll demonstrate the usage of the Intl.Collator object to sort words in alphabetical order.
JavaScript
const words = [
"JavaScript",
"Program",
"to",
"Sort",
"Words",
"in",
"Alphabetical",
"Order",
];
const collator = new Intl.Collator(undefined, { sensitivity: 'base' });
const sortedWords = words.sort(collator.compare);
console.log(sortedWords);
Output[
'Alphabetical',
'in',
'JavaScript',
'Order',
'Program',
'Sort',
'to',
'Words'
]
Using a Trie Data Structure for Sorting
A Trie (or prefix tree) is a tree-like data structure that stores a dynamic set of strings, where each node represents a single character of a word. By inserting words into a Trie and then performing an in-order traversal, we can collect the words in alphabetical order.
Here’s how you can implement this approach in JavaScript:
- Define the Trie Node and Trie Classes: Create a class to represent each node in the Trie and another class for the Trie itself.
- Insert Words into the Trie: Add words to the Trie by inserting characters into the appropriate nodes.
- Perform an In-Order Traversal: Traverse the Trie to collect words in alphabetical order.
Example:
JavaScript
class TrieNode {
constructor() {
this.children = {};
this.isEndOfWord = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (let char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEndOfWord = true;
}
traverseAndCollect(node = this.root, prefix = '', result = []) {
if (node.isEndOfWord) {
result.push(prefix);
}
for (let char in node.children) {
this.traverseAndCollect(node.children[char], prefix + char, result);
}
return result;
}
sortWords() {
return this.traverseAndCollect();
}
}
// Example usage
const words = [
"JavaScript",
"Program",
"to",
"Sort",
"Words",
"in",
"Alphabetical",
"Order",
];
const trie = new Trie();
words.forEach(word => trie.insert(word));
const sortedWords = trie.sortWords();
console.log(sortedWords);
Output[
'JavaScript',
'Program',
'to',
'Sort',
'Words',
'in',
'Alphabetical',
'Order'
]
Similar Reads
JavaScript Program to Sort Strings in Alphabetical Order Ignoring Case
In this article, we are given an array of strings, you need to sort the given array of strings containing both uppercase and lowercase characters in ascending order by ignoring the case in JavaScript. Example 1: Input :- arr = ["Geeks", "for", "geeks", "is", "The", "Best"] Output :- [ 'Best', 'for',
3 min read
JavaScript Program to Sort the Elements of an Array in Ascending Order
Sorting JS Array in ascending order refers to arranging elements from the smallest to largest element. We can use JS array sort, sorting algorithms, and external libraries to sort array. 1. Using JS Array.sort() Method- Mostly UsedPass the comparator function in array.sort() to sort the array in asc
2 min read
JavaScript Program to Print the Frequency of Each Character in Alphabetical Order
The operation involves counting how many times each character in alphabetic characters in a given string. Using Object (Simple and Efficient for Small to Moderate Strings)Object in JavaScript allow storing key value pairs. So we use items as keys and their frequencies as values. [GFGTABS] JavaScript
2 min read
JavaScript Program to find Smallest and Largest Word in a String
We are going to discuss how can we find the Smallest and Largest word in a string. The word in a string which will have a smaller length will be the smallest word in a string and the word that has the highest length among all the words present in a given string will be the Largest word in a string.
5 min read
JavaScript Program to Find Shortest Distance Between Two Words in an Array of Words
Given an array of words and two target words, the task is to find the shortest distance (minimum number of words) between the two target words in the array. The distance is calculated by counting the number of words between the two target words, excluding the target words themselves. Approaches to f
2 min read
JavaScript Program to Print the First Letter of Each Word
Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word. Examples of Printing the First Letter of Each Word Table of Conten
3 min read
JavaScript Program to Sort an Associative Array by its Values
In Javascript, "arrays" are indexed by numerical values, while "objects" are essentially what you might refer to as associative arrays. It's important to note that "objects" do not have a guaranteed order. In this article, we will learn how can we sort an associative array by its values. Table of Co
4 min read
JavaScript Program to Compare Two Strings Lexicographically
This JavaScript program compares two strings lexicographically, meaning it checks if one string comes before or after the other in alphabetical order. Lexicographical comparison is based on the Unicode value of each character in the strings. The program should return a positive value if the first st
1 min read
JavaScript Program to Sort the 2D Array Across Rows
We will see how to sort the 2D Array across rows using a Javascript program. we can sort the 2D Array Across Rows in many ways including Bubble Sort Algorithm, Array.prototype.sort() method, Insertion Sort Algorithm, Using the Selection Sort Algorithm, and Merge Sort Algorithm. Example: Input:[[8 5
6 min read
JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
In this article, we have given a string and the task is to write a javascript program to reverse only the consonants of a string without affecting the other elementsâ positions and printing the output in the console. Examples:Input: helloOutput: lelhoExplanation: h,l,l are consonants in the given st
6 min read