1

I've been trying to see what's happening exactly with this code by stepping through it in Google Chrome. How and when does the sort method move each element in this array?

I cannot figure out why "b" is index 0 and why "a" is index 1 initially. Logically a should be 10.99 and "b" should be 5.99. And where is the data getting temporarily stored as it moves through the elements in the array? Also, when are the elements "shifting"?. Meaning what is happening through each time the a,b parameters move to compare the next a,b set of numbers of the prices array in this sort() function?

const prices = [10.99, 5.99, 3.99, 6.59, 8.49, 1.99, 12.99];

const sortedPrices = prices.sort((a, b) => {   
    if (a > b) {
        console.log("a is greater than b. a moves right, b moves left.");
        return 1;
    } else if (a === b) {
        console.log("a is the same value as b.");
        return 0;
    } else {
        console.log("a is less than b. a moves left, b moves right.");
    return -1;
    }
});

console.log(sortedPrices);

This image is the sorting order as I followed what numbers were compared to each other. The beginning of the arrow represents "a" and the end of the arrow with the "<" represents "b". Where it gets confusing on top of trying to understand the above issue, is why when the sort method gets to 1.99, why does it skip 8.49 and get compared to 6.59?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • It shouldn't matter what items get compared, just be consistent in what the callback returns. – Niet the Dark Absol Jun 20 '21 at 16:06
  • Thanks for the reply, I understand what you mean as far as being consistent. But, how do I know what logic to apply in the future of what the returns should be if I don't understand why "a" is the second element in the array and "b" is the first? Is it always chosen like this in a comparator function? – Nate Sawyer Jun 20 '21 at 16:24
  • 1
    @NateSawyer nope, it doesn't, it depends on chosen sorting algorithm, which are different for different language implementations and engines, some engines use different algorithms depending on entered array/data – Allure Jun 20 '21 at 16:33
  • @Allure Awesome, well it's good to know where to be able to dive deeper into this. Thanks for pointing me in the right direction! :) – Nate Sawyer Jun 20 '21 at 16:40

1 Answers1

0

partially it is explained there: Javascript Array.sort implementation?

initial values are different for different implementations in different engines look at the native code of this method, which are provided there: Javascript native sort method code

also I recommend read more about sorting algorithms

Allure
  • 513
  • 2
  • 12