“Sort()” of confused
I was reviewing javaScript .sort() method, and I got confusion.
MDN Web Docs states (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) following:
- If
compareFunction(a, b)
returns less than 0, leavea
andb
unchanged. - If
compareFunction(a, b)
returns 0, leavea
andb
unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAScript standard only started guaranteeing this behavior in 2019, thus, older browsers may not respect this. - If
compareFunction(a, b)
returns greater than 0, sortb
beforea
.
And above rule can be written as:
const array1 = [ 5, 3, 8 ];// for Ascending order:
console.log( array1.sort((a, b) => a - b) ); // [3, 5, 8]// for Descending order:
console.log( array1.sort((a, b) => b - a) ); // [8, 5, 3]
Perfect!!!
But when I threw in a console.log(), I found myself saying… huh?
In line 6, I added console.log() to see the values of “a” and “b”, and they weren’t what I expected.
This is what I expected: during first loop: “a”: 5(first element in array), “b”: 3.
But what I am seeing in console.log results are:
1st loop: “a”: 3, “b”: 5. a-b < 0, keep the order — Results [3, 5, 8]
2nd loop: “a”: 8, “b”: 3. a-b > 0, sort b before a — Results [3, 5, 8]
3rd loop: “a”: 8, “b”: 5. a-b > 0, sort b before a — Results [3, 5, 8]
If I sort [ 8, 5, 3 ], sort completes in two loop:
So, there must be a comparison algorithm that sort() method uses, and I was quite surprised how it was different than what I expected. So, threw in console.log() around. You might see something very interesting.