Arr.sort((a,b) => a-b); explanation

Just use debugger and watch the values. It’s not top secret.

(() => {
    const sorted = [3,6,9,4,6].sort(function(a, b) {
        return a - b;
    });
    console.log(sorted);
})();

1st iteration:
a = 6, b = 3 // return 3

2nd iteration:
a = 9, b = 6 // return 3

3rd iteration:
a = 4, b = 9 // return -5

4th iteration:
a = 4, b = 6 // return -2

5th iteration:
a = 4, b = 3 // return 1

6th iteration:
a = 6, b = 6 // return 0

7th iteration:
a = 6, b = 9 // return -3

[ 3 ] [ 6 ] [ 9 ] [ 4 ] [ 6 ]
[ b ] [ a ] [ 9 ] [ 4 ] [ 6 ] ( 6-3 is positive ) (move b,a right)

[ 3 ] [ 6 ] [ 9 ] [ 4 ] [ 6 ]
[ 3 ] [ b ] [ a ] [ 4 ] [ 6 ] ( 9-6 is positive ) (move b,a right)

[ 3 ] [ 6 ] [ 9 ] [ 4 ] [ 6 ]
[ 3 ] [ 6 ] [ b ] [ a ] [ 6 ] ( 4-9 is negative )
[ 3 ] [ 6 ] [ 4 ] [ 9 ] [ 6 ] (swap b,a) (a remains 4 until a-b is positive, b is next value to left)

[ 3 ] [ 6 ] [ 4 ] [ 9 ] [ 6 ]
[ 3 ] [ b ] [ a ] [ 9 ] [ 6 ] ( 4 - 6 is negative)
[ 3 ] [ 4 ] [ 6 ] [ 9 ] [ 6 ] (swap b,a) (a remains 4 until a-b is positive, b is next value to left)

[ 3 ] [ 4 ] [ 6 ] [ 9 ] [ 6 ]
[ b ] [ a ] [ 6 ] [ 9 ] [ 6 ] ( 4 - 3 is positive) (return back to when a-b was last positive)

[ 3 ] [ 4 ] [ 6 ] [ 9 ] [ 6 ]
[ 3 ] [ 4 ] [ b ] [ 9 ] [ a ] (6 - 6 is 0) (keep same) (move right)

[ 3 ] [ 4 ] [ 6 ] [ 9 ] [ 6 ]
[ 3 ] [ 4 ] [ 6 ] [ b ] [ a ] ( 6 - 9 is negative)
[ 3 ] [ 4 ] [ 6 ] [ 6 ] [ 9 ] (swap)

completed.

4 Likes