Reputation: 51
i was wondering how javascript Array sort method works, when a custom sorting function is specified like the one below :
arr = [1, 5, 122, 12];
arr.sort(function (a,b){return a-b;});
if it only accepts two arguments a,b (1,5) in "arr", i know that javascript allow more arguments than those specified in the function. but how sort function is acting, does it compares 1,5 then 122,12, store result in a place then redo the comparison.
Upvotes: 2
Views: 299
Reputation: 146660
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 from a
or you may want to use Spanish collation and make a
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 before apple
:)
However, the sort algorithm itself (quicksort, etc.) is an implementation detail that normally doesn't matter for your business logic.
Upvotes: 2
Reputation: 7360
It is well explained in the MDN documentation:
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;});
Upvotes: 0