Search code examples
javascriptsortingasciialphabetical-sortalphabetized

Sort String Alphabetically Regardless of Capitalization - JavaScript


Working on this codewars challenge.

Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!

The input is restricted to contain no numerals and only words containing the english alphabet letters.

Example:

alphabetized("The Holy Bible") // "BbeehHilloTy"

I started with:

function alphabetized(s) {
    s = s.replace(/\s/g, "").toLowerCase();
    return s.split("").sort().join("");
}

console.log(alphabetized("The Holy Bible"));

But of course we want to return BbeehHilloTy, maintaining capitalization of the original characters.

Frankly I'm not understanding why the desired outcome should be BbeehHilloTy.

If we're not sorting according to the ASCII character code values, then what determines whether or not a capital letter should appear in front of a lowercase letter in the new string?


Solution

  • Here's a method that creates a stable sort by comparing the characters' indexes in the string if they are equal:

    function alphabetized(s){
      s = s.replace(/\s+|\W+|\d+|[_]+/g, "");
      return s.split('')
        .map(function(x, i){ return [x, i]; })
        .sort(function([a, i], [b, j]){
          a = a.toLowerCase();
          b = b.toLowerCase();
          if (a == b)
            return i - j;
          else if (a < b)
            return -1;
          else
            return 1;
          })
          .map(function([x, i]){ return x; })
          .join('');
    }
    
    console.log(alphabetized("The Holy Bible"));