Sort a string alphabetically using a function

前端 未结 3 1219
忘掉有多难
忘掉有多难 2021-02-05 01:55

Imagine you were given a string and you had to sort that string alphabetically using a function. Example:

sortAlphabets( \'drpoklj\' ); //=> returns \'djklopr         


        
3条回答
  •  [愿得一人]
    2021-02-05 02:48

    Newer browsers support String.prototype.localeCompare() which makes sorting utf8 encoded strings really simple. Note that different languages may have a different order of characters. More information on MDN about localCompare.

    function sortAlphabet(str) {
      return [...str].sort((a, b) => a.localeCompare(b)).join("");
    }
    
    console.log(sortAlphabet("drpoklj")); // Logs: "djklopr"

    If you only have to support ascii strings then the default sorting implementation will do.

    function sortAlphabet(str) {
      return [...str].sort().join("");
    }
    

提交回复
热议问题