Case-sensitive sort in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of string literals like this −

const arr = ['1185 Design','3 D Exhibits','44Doors', '4Concepts','ABC Data','acceleration'];

We are required to write a JavaScript function that takes in one such array and sorts the array inplace.

The sorting function should be such that all the strings starting with special characters, numerals appear first.

Then, after that strings should appear in alphabetical order and if we have two strings starting with the same alphabet but different cases, then the string starting with lowercase alphabet should appear first.

Example

The code for this will be −

const arr = ['1185 Design','3 D Exhibits','44Doors', '4Concepts','ABC Data','acceleration'];
const caseSensitiveSort = (arr = []) => {
   const sorter = (a, b) => {
      if (a === b){
         return 0
      };
      if (a.charAt(0) === b.charAt(0)){
         return sorter(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);
   };
   arr.sort(sorter);
}
caseSensitiveSort(arr);
console.log(arr);

Output

And the output in the console will be −

[
   '1185 Design',
   '3 D Exhibits',
   '44Doors',
   '4Concepts',
   'acceleration',
   'ABC Data'
]
raja
Published on 21-Nov-2020 14:52:45
Advertisements