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.