JavaScript Program to Sort Strings in Alphabetical Order Ignoring Case
Last Updated :
18 Sep, 2023
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', 'Geeks', 'geeks', '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 "Geeks" 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
- Using a comparator function localeCompare()
- Without using the comparator function
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
Javascript
let arr = [ "Geeks" , "for" , "geeks" , "is" , "The" , "Best" ];
arr.sort( function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
console.log(arr);
|
Output
[ 'Best', 'for', 'Geeks', 'geeks', '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
Javascript
let arr = [ "Geeks" , "for" , "geeks" , "is" , "The" , "Best" ];
arr.sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
console.log(arr);
|
Output
[ 'Best', 'for', 'geeks', 'Geeks', 'is', 'The' ]
Share your thoughts in the comments
Please Login to comment...