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?