jskatas.org Continuously Learn JavaScript. Your Way.

Array API: array.sort() can take a compare function

Passing a callback to the sort() function, allows for any custom sorting.

Donate to NGO Julenka. Support Ukranians in need. Julenka is an NGO which my brother founded in 2011 to support Ukranian families and kids in need.

[].sort() can take a compare function

the compare function

  • can be given as the only parameter to sort() (and gets used by it)
  • is called with two values to be compared
  • is called multiple times (depending how the sort algorithm is implemented)

the return value of the compare function indicates how the two values compare

both compared values match, they are the same
  • when it returns 0
  • when undefined is returned
  • when null is returned

examples

  • sort numbers
  • sort number-like values
  • custom compare algorithm

Links

Very detailed description of how `sort()` works.
Announcement of this kata on twitter.