Home > Net >  Order of parameters in javascript array sort method is not intuitive
Order of parameters in javascript array sort method is not intuitive

Time:12-15

So I create two objects:

var obj1 = {
    "id" : 123,
    "name" : "Hello"
}

var obj2 = {
    "id" : 456, 
    "name" : "Goodbye"
}

Then I insert these into an array:

var arr = [obj1, obj2];

I then store the result of sorting into a variable and log to the console:

var test = arr.sort(function(x, y) {
    console.log("x ", x)
    console.log("y ", y)
});

console.log(test);

The result is:

x  {id: 456, name: 'Goodbye'}
y  {id: 123, name: 'Hello'}

I was expecting the order to be the same as the occurrence of the objects in the array since I have not defined any sort criterion. Why is the order as such?

CodePudding user response:

Output

So as you can see it compares second to first it then compares third to second. The sort is complete.

Doing the same with numbers and actually sorting

enter image description here

you get

position 2 compares to position 1 and returns -1 so its smaller and must moves into position 1

enter image description here

[2,3,1,6,5]

position 3 compares to position 1 and returns -1 so its smaller and must moves into position 1

enter image description here

[1,2,3,6,5]

position 4 compares to position 1 and returns 5 so its larger and must remain in place

enter image description here

[1,2,3,6,5]

position 4 compares to position 2 and returns 4 so its larger and must remain in place

enter image description here

[1,2,3,6,5]

position 4 compares to position 3 and returns 3 so its larger and must remain in place

enter image description here

[1,2,3,6,5]

position 4 has nothing in front of it to compare to so we move to the next position

position 5 compares to position 1( of the original array) and returns 2 so its larger and it uses normal binary search logic to try another position (next compare)

enter image description here

[1,2,3,6,5]

finally position 5 compares to position 4 and returns -1 so it knows it must move into position 4

enter image description here

[1,2,3,5,6]

  • Related