Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda