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

238
Visualizações
Why isn't the order of my array preserved after it's created in javascript

I'm working on a basic coding problem, and in my solution I've used a for loop to iterate over an array and create smaller arrays for comparison within it:

    for (let i = 0; i < words.length - 1; i++) {
        const curr = words[i]
        const next = words[i + 1]
        const testArray = [curr, next]
        const sortTest = testArray.sort()
        console.log(testArray)
        console.log(`2: ${sortTest}`)
    }
};

Given a simple array words = ["cool", "cat"], I expect the testArray = ["cool", "cat"] and sortTest = ["cat", "cool"]. However, no matter how I build the array testArray is logging to the console as ["cat", "cool"]. For my solution to work the order of the created arrays must be preserved, and I can't figure out why they're being automatically sorted. To be perfectly clear, I understand how the sort() method works, that is not the problem. The problem is the array being sorted upon being made. I need the order to be as I set it with the value of the variable 'curr' set at index 0 and the value of the variable 'next' set at index 1. As I mentioned above, this is not the case no matter how I declare it.

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