Confusing Point About Array Sort Method In Javascript
Solution 1:
when a custom sorting function is specified
This is not correct. You provide a function to compare items:
arr.sort() arr.sort(compareFunction)
compareFunction
Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
The sort algorithm itself is hard-coded in native implementation and cannot be changed. Implementations may even choose to pick different algorithms depending on data types or array length.
The rationale is that you may have different needs:
You may want to use binary collation and make
A
different froma
or you may want to use Spanish collation and makea
identical toรก
.You may want to sort custom objects:
[ { city:"Madrid", population:4000000 }, { city:"Cairo", pages:15000000 } ]
Or you may want to sort fruits and make
pear
come beforeapple
:)
However, the sort algorithm itself (quicksort, etc.) is an implementation detail that normally doesn't matter for your business logic.
Solution 2:
It is well explained in the MDN documentation:
- If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
- If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.
- If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
So there is nothing to do with having more than two arguments.
If you are asking in which order it compares them, it is up to implementation. You can find it doing a console.log in the function:
arr = [1, 5, 122, 12];
arr.sort(function (a,b){console.log('Comparing a:', a, 'and b:', b); return a-b;});
Post a Comment for "Confusing Point About Array Sort Method In Javascript"