Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Sort a string alphabetically using a function

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

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

What would be the best way to do this?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can use array sort function:

var sortAlphabets = function(text) {
    return text.split('').sort().join('');
};

STEPS

  1. Convert string to array
  2. Sort array
  3. Convert back array to string

Demo

over 4 years ago · Santiago Trujillo Relatório

0

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("");
}
over 4 years ago · Santiago Trujillo Relatório

0

As previous answers have shown, you convert the string to an array of single-character strings, sort that, and then recombine it into a string. But, using split isn't the best practice way to do that first step, because a JavaScript string is a series of UTF-16 code units with invalid surrogate pairs tolerated, and split("") splits up surrogate pairs into their individual code units, potentially separating them, thus breaking the code point (loosely: character) they're supposed to form as a pair. So if you have an emoji in the string (for instance) or any of hundreds of thousands of characters in non-Western scripts, those can get broken.

In ES5 and earlier, correctly splitting the string required that you detect and handle surrogate pairs to ensure they stayed together, which was a bit of a pain and involved checking charCodeAt for specific ranges of values.

As of ES2015+, it's really easy: You just use the string's iterator, which is defined to provide each code point in the string, whether that's a single code unit or two. To get an array of the code points, you can use the iterator via spread notation ([...str]) or Array.from (Array.from(str)).

So using that, we get:

function sortAlphabets(str) {
    return [...str].sort((a, b) => a.localeCompare(b)).join("");
}

Live Example:

// Using the iterator
function sortAlphabets(str) {
    return [...str].sort((a, b) => a.localeCompare(b)).join("");
}

// Using split("")
function sortAlphabetsUsingSplit(str) {
    return str.split("").sort((a, b) => a.localeCompare(b)).join("");
}

const str = "😀देवनागरी😃";
console.log("Original string    : " + str);
console.log("Using the iterator : " + sortAlphabets(str));
console.log("Using split('')    : " + sortAlphabetsUsingSplit(str));

Note how using split, some of the characters have gotten mangled.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda