Confusion in javascript array sorting method

I was wondering how the javascript Array sort method works when a custom sort function is specified as shown below:

arr = [1, 5, 122, 12]; arr.sort(function (a,b){return ab;}); 

if it takes only two arguments a, b (1,5) in "arr", I know that javascript allows more arguments than those specified in the function. but how does the sort function work, does it compare 1.5, then 122.12, save the result in place, then repeat the comparison.

+2
source share
2 answers

when a custom sort function is specified

This is not true. You provide a function to compare elements :

 arr.sort() arr.sort(compareFunction) 

compareFunction

Defines a function that determines the sort order . If omitted, the array is sorted by each character. Code point Unicode value, in accordance with the conversion of the string of each element.

The sorting algorithm itself is hardcoded in its own implementation and cannot be changed. Implementations may even choose different algorithms depending on data types or array length.

The rationale is that you may have different needs:

  • You can use binary sorting and make A different from A , or you can use Spanish sorting and make A identical to á .

  • You can sort custom objects:

     [ { city: "Madrid", population: 4000000 }, { city: "Cairo", pages: 15000000 } ] 
  • Or you can sort fruits and do pear before apple :)

However, the sorting algorithm itself (quicksort, etc.) is an implementation detail that usually does not matter to your business logic.

+2
source

This is well explained in the MDN documentation :

  • If compareFunction (a, b) is less than 0, sort a with a lower index than b, i.e. first comes.
  • If compareFunction (a, b) returns 0, leave a and b unchanged relative to each other, but sorted relative to all different elements.
  • If compareFunction (a, b) is greater than 0, sort b with a lower index than a.

Thus, there is nothing to do with having more than two arguments.

If you ask in what order he compares them, it depends on the implementation. You can find that it executes console.log in a function:

 arr = [1, 5, 122, 12]; arr.sort(function (a,b){console.log('Comparing a:', a, 'and b:', b); return ab;}); 
0
source

Source: https://habr.com/ru/post/1275551/


All Articles