Home > Net >  Sorting a string into a group of upper and lowercase letters - Javascript
Sorting a string into a group of upper and lowercase letters - Javascript

Time:03-04

I have a function below which is a string that is sorted alphabetically, with the uppercase letter coming before its lowercase letter.

group('aaAbbBCCcDdEE') //should return 'AaaBbbCCcDdEE'


   function group(string){
return string.split("").sort(function(a, b) {
    return a - b;
  }) .join("");
}
  • what is the best method available to sort this?

thanks.

CodePudding user response:

Add check to see what you are working with. The part you really care about is if a and b are the same character and if one of them is upper and one is lower.

const result = 'aaAbbBCCcDdEE'.split('').sort((a, b) => {
  // if they are the same, nothing to do
  if (a === b) return 0;
  // normalize the letters
  const uA = a.toUpperCase();
  const uB = b.toUpperCase();
  // if they are the same letter when normalized, figure out what one is upper
  if (uA === uB) return uA === a ? -1 : 1
  // if not, just sort them by alphabet
  return uA.localeCompare(uB);
}).join('');
console.log(result);

CodePudding user response:

You can cerate your custom sort method which works on Ascii values of characters

a -> 97

A-> 65

So to fulfil your need, we can simply, set the lowercase value codes to be sit in between two consecutive Uppercase letters

i.e A -> 65, a -> 65.5, B-> 66, b-> 66.5 ...... Z-> 90, z-> 90.5

Lets move to code now

function getSortableCode(c) 
{ 
  const code = c.charCodeAt(0); 
  return code >= 97 ? code - 31.5 : code;
} 

function doSort(str)
{
  return str.split('').sort((a,b) => getSortableCode(a) - getSortableCode(b));
}
console.log('aaAbbBCCcDdEE after sorting becomes: '   doSort('aaAbbBCCcDdEE'));

Please mark the answer as accepted if it helps

CodePudding user response:

I had a similar idea. Checking if the letters are the same but different casing, use sort by their ASCII value.

    group('aaAbbBCCcDdEE') //should return 'AaaBbbCCcDdEE'


   function group(string){
return string.split("").sort(function(a, b) {
    return a !== b && a.toLowerCase() === b.toLowerCase() ? a.charCodeAt(0) - b.charCodeAt(0) : a - b;
  }) .join("");
}

CodePudding user response:

Thanks - All codes work great - Appreciated!

  • Related