Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!