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 = ["Beginner", "for", "Beginner", "is", "The", "Best"] Output :- [ 'Best', 'for', 'Beginner', 'Beginner', 'is', 'The' ] Explanation: In the input array after looking at starting character of each string we find that : B < F < G < I <T. So "Best" will come first followed by "For" then "Beginner" two times then "Is" and finally "The"
Example 2:
Input :- arr = ["Hey", "How", "You", "Doing" ] Output :- ['Doing', 'Hey', 'How', 'You']
Approaches to sort strings in alphabetical order ignoring case in JavaScript
Table of Content
- Using a comparator function
- Without using the comparator function
- Using Array.sort() with Intl.Collator
Approach 1: Using a comparator function
In this approach, we Initialize the array and use the sort method to sort the array in alphabetical order ignoring case. The sort method then takes a comparator function as its argument. The comparator function compares two elements of the array a and b and then it returns a negative number if a comes before b, a positive number if a comes after b, or 0 if both a and b are equal.
Example: Below is the implementation of this approach
let arr = ["Beginner", "for", "Beginner", "is","The","Best"];
arr.sort(function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
console.log(arr);
Output
[ 'Best', 'for', 'Beginner', 'Beginner', 'is', 'The' ]
Approach 2: Without using the comparator function
Convert the strings to lowercase by using the toLowerCase method, and then compare them using the ternary operator ? . If the lowercase version of string a comes after the lowercase version of string b, then return 1 which means that a should come after b in the sorted array. Otherwise, return -1 meaning that a should come before b in the sorted array.
Example: Below is the implementation of this approach
let arr = ["Beginner", "for", "Beginner", "is","The","Best"];
arr.sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
console.log(arr);
Output
[ 'Best', 'for', 'Beginner', 'Beginner', 'is', 'The' ]
Approach 3: Using Array.sort() with Intl.Collator
Using Array.sort() with Intl.Collator, initialize Collator with { sensitivity: ‘accent’ } to perform a case-insensitive comparison. Then, sort the array of strings, considering language-specific rules for sorting while ignoring case differences.
Example:
const strings = ["Apple", "banana", "Orange", "grape"];
const collator = new Intl.Collator(undefined, { sensitivity: 'accent' });
strings.sort(collator.compare);
console.log(strings);
Output
[ 'Apple', 'banana', 'grape', 'Orange' ]
Contact Us