0

I'm wondering WHY when I sort items in the original array they show up in a weird order when processing but the result is correct.

Here's the code

var arr = [100, 8, 20, 12];

var x = 1;

console.log("Original Array = " + arr)
arr.sort(function(a,b){

    console.log("Set " + x++) //for tracking purposes
    console.log(a, b)
    console.log("a-b = " + (a-b))
    return a-b;
})

console.log(arr)

I've tried this on both SoloLearn and on Chrome to see if it had something to do with the browser itself but I get the same results

RESULT:

screenshot from SoloLearn

I want to understand why this behavior of sorting happens (a=8 and b=100...etc)

Any help or reference would be greatly appreciated.

  • because the `function(a,b) {...}` is used **inside** the sort processing, not after – Mister Jojo Mar 03 '21 at 04:31
  • @MisterJojo right....I understand that part of the function being **inside** the sort function.....however, that still wouldn't explain why somehow 8 comes before 100 in set 1. Shouldn't 'a' still be 100 and 'b' still be 8? I would assume it reads " function(100,8){...} ". I understand browsers have their own sorting mechanism/algorithm...but that shouldn't disrupt the order in which the numbers are input into the function. Thank you though....I did think about the fact that the compare function was inside the sort function and how that could interfere in some way. Still scratching my head lol – Andres Alvarez Mar 03 '21 at 13:58
  • `8` comes before `100` because this kind of algorithm is written in assembler and the arguments are always passed by a LIFO stack – Mister Jojo Mar 03 '21 at 15:11

0 Answers0