Case-sensitive sort in JavaScript


The problem statement says to perform case sensitive sorting in javascript on the array of strings given as an input source by the user .

The problem statement wants the developer to perform a case sensitive sorting where all the special characters and numerals should appear first and sort first inplace followed by the sorting of lowercase characters first before the upper case characters .

Is JavaScript Case Sensitive ?

Before moving forward towards the problem statement we need to understand more about the word “case-sensitive” in the context of JavaScript initially. JavaScript is a case sensitive programming language which understands uppercase and lowercase very differently in greater depth.

For example , given some variety of variables in console , JavScript recognises each with its unique character molding:

Example

const language = "JavaScript";
const Language = "React";
const x = 100;

console.log(language);
console.log(Language);
console.log(x);

Output

JavaScript
React
100

Is Sorting Method Case-Sensitive ?

The sort method in javascript sorts the array inplace and results in the sorted array in ascending order by default . But JavaScript language has a catch here , it first converts every single element you want to sort into a string data type and then the sorting is performed.

In JavaScript the sort method in behind the scenes do not just do comparison like many other programming languages do for sorting but here once each element is when converted into string initially these conversions are solely based on UTF-16 followed by the order of element comes in the table while converting , that decides the sorting parameter of sort method in JavaScript. UTF-16 allows more characters and emojis in your domain , hence efficient and large scale sorting is wished for.

The default behavior of the sorting method is to sort uppercase letters first before the lowercase letters . For example ,

Example

const sortString = ["Banana", "apple", "Kiwi", "grapes", "Ice-cream"];
console.log(sortString.sort());

Output

['Banana', 'Ice-cream', 'Kiwi', 'apple', 'grapes']

The default behavior also lies in sorting the numbers first before the uppercase letters followed by lowercase letters at the last.For example ,

Example

const sortString = [ "Banana" , "1" , "apple" ];
console.log(sortString.sort());

Output

[ '1', 'Banana', 'apple' ]

What is the localeCompare Method?

The localCompare method is an inbuilt string comparison method in javascript that is used to compare and sort the string based on the every occurrence of alphabet returning a number which can be less than 0 , greater than 0 or equal to 0 denoting which string comes before , after or equal to which other string you are comparing it with in your written customized sort function. The localeCompare method has two things : Compare String and reference String where compareString is given as a parameter and reference string is used to call the localeCompare method with compareString as the parameter.

The syntax looks like ,

referenceString.localeCompare(comparisonString)

The several cases are made according to the syntax mentioned returning a number based on ,

  • If reference string occurs before compare string , the method returns negative -1

  • If reference string occurs after compare string , the method returns positive 1

  • If reference string and compare string are equal , the method returns neutral 0

Example

The example without localeCompare looks like ,

const sortString = [ "Banana" , "1" , "apple" ];
console.log(sortString.sort());

Output

[ '1', 'Banana', 'apple' ]

Example

The example with localeCompare looks like ,

function compareSort(a,b)
{
   return a.localeCompare(b);
}

const sortString = [ "Banana" , "1" , "apple" ];
console.log(sortString.sort(compareSort));

Output

[ '1', 'apple', 'Banana' ]

Algorithm

The algorithm for the particular problem statement involves recursion technique to repeat a certain helper function for every comparison that happens for case sensitive sorting.

Step 1 : Declare a function with name caseSensitiveSort that takes a string array as an input.

Step 2 : Return a customized sorting helper function from it as an argument using sort method of javascript

Step 3 : Declare a customized sorting function with name sensitiveSorter that takes in two arguments a and b to compare every two consecutive elements present in the string array .

Step 4 : The helper or customized sorting function is a recursive function in nature , thus produces some base case for the recursion technique ie. if both the first and second elements are the same , it concludes there is only one element present in this string array.

Step 5 : Match the first character of both the consecutive elements using charAt method and if the match is successful splice out the first character of both the elements using splice method of javascript to perform the recursive nature of helper function sensitiveSorter again with the next characters of both elements you are trying to sort for.

Step 6 : If the first characters of both the elements are not matched , convert them into the lowercase and if they match successfully then , check if first character of the first element is lowercase and first character of second element is uppercase using regex expression against the test method in javascript which concludes that the first element will come before second element hence returning -1 negative number that is compatible to the localeCompare method which we will see in later steps of algorithm.

Step 7 : If the first characters of both the elements are not matched , convert them into the lowercase and if they match successfully then , check if first character of the first element is uppercase and first character of second element is lowercase using regex expression against the test method in javascript which concludes that the first element will come after second element hence returning +1 positive number that is compatible to the localeCompare method which we will see in later steps of algorithm.

Step 8 : Later use the localeCompare method in javascript to sort the two consecutive elements alphabetically based on the occurrence of each letter returning a number either less than 0 , greater than 0 or equal to 0 whose cases are already handled in the steps mentioned above.

Example

function sensitiveSorter(a,b)
{
   if(a===b)
      {
      return 0 ;
     }
   
   if(a.charAt(0)===b.charAt(0))
      {
      return sensitiveSorter(a.slice(1) , b.slice(1));
      } 
   
   if (a.charAt(0).toLowerCase() === b.charAt(0).toLowerCase() )
      {
      if(/^[a-z]/.test(a.charAt(0)) && /^[A-Z]/.test(b.charAt(0))) 

         {
         return -1 ;
         }

   if(/^[a-z]/.test(b.charAt(0)) && /^[A-Z]/.test(a.charAt(0)))

   {
         return -1 ;
      }

   }

   return a.localeCompare(b);
}


function caseSensitiveSort(stringArray)
{
   return stringArray.sort(sensitiveSorter);
}

const stringArray = ["123" , "Hello" , "1TuorialsPoint" , "apple" , "$1jain" , "JAVASCRIPT" ];

const sensitiveSortedResult = caseSensitiveSort(stringArray);

console.log(sensitiveSortedResult);

Output

[ '$1jain', '123', '1Tutorialspoint', 'apple', 'Hello', 'JAVASCRIPT' ]

The following mentioned code is the straight forward code one can think of while looking at the problem statement , later you can ofcourse optimize it to the better quality of space and time making it more efficient and high quality.

In the above code we have declared a function taking in the string array input . Then we go indirectly by knowing the sorting mechanism and sorting the array using if -else ladder with javascript methods like splice , charAt and most importantly localeCompare javascript inbuilt method to whole the case sensitive sorting in one go.

Time and Space Complexity

Array.sort () method is based on the Time sort algorithm , giving the time complexity of O (n log n) and in the worst case , time complexity goes to O ( n^2) whereas the time complexity of charAt method is O(1) as a constant and splice method performs O(n) worst case time complexity . And the whole recursive function gives time complexity of O (2^n) giving sub branches of recursive function degrading the time complexity. Hence the result is less optimized but the sort method can perform case sensitivity in relation to problem statements like this only.

Conclusion

This is how we can solve the above problem statement thinking logically and in the context of coding taking help of javascript method sort and other inbuilt methods in its most efficient use case .

Updated on: 22-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements