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

202
Visualizações
Javascript Sort by character appearance position

I have the following code:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
    const input = 'hello world';
    document.getElementById("demo").innerHTML = sortAlphabets(input);

    function sortAlphabets(input) {
        return input.split('').sort().join('');
    };
</script>

</body>
</html>

The result is: dehllloorw

But I want to change it to sort by character appearance position. The result should be: hellloowrd

How can I do that?
Really appreciated.

Thank you.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a compare function with .sort and inside that function you can use input.indexOf to get the index of the first appearance of the character in the input string.

input.split('').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')

EDIT

If you want spaces to be removed just use a filter after the split.

input.split('').filter(c=>c!==' ').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')
about 4 years ago · Juan Pablo Isaza Relatório

0

You need a custom sort function, here will compare by index

const input = 'hello world';

let splited = input.split('').map(e => e.trim());

let sorted = splited.sort((a, b) => {
  return splited.indexOf(a) - splited.indexOf(b);
}).join('');

console.log(sorted);

about 4 years ago · Juan Pablo Isaza 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