0

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.

Geoff7709
  • 1
  • 1
  • 2
    [_"The `sort()` method sorts the elements of an array in place ..."_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Peter Seliger Feb 27 '22 at 00:08
  • I understand that. 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. – Geoff7709 Feb 27 '22 at 21:19
  • There is exactly on time where the order meets the OP's wish ... right after declaring `const testArray = [curr, next];`. Already with `const sortTest = testArray.sort();`, `testArray` will be altered unless `[curr, next]` were not already in correct order; and `sortTest` is always just a reference of the mutated/altered `testArray`. – Peter Seliger Feb 27 '22 at 22:55
  • In order to not alter/mutete the initial state of **testArray** the OP needs to create a shallow copy of the latter which then gets sorted and assigned … **const testArray = [curr, next]; const sortTest = Array.from(testArray).sort();** – Peter Seliger Feb 28 '22 at 01:05
  • _"The problem is the array being sorted upon being made. "_ ... of cause not ... the reason that it appears to the OP like this is the already mentioned [In-place algorithm](https://en.wikipedia.org/wiki/In-place_algorithm) ... `sort` mutates the array itself. Just do `console.log(testArray);` right before the sorting, then log again after the sorting, and in addition `console.log(testArray === sortTest);` in order to understand that the latter is just a reference of/to the former. – Peter Seliger Feb 28 '22 at 08:05
  • This was amazingly helpful - thank you so much! – Geoff7709 Feb 28 '22 at 21:12

0 Answers0