Array.prototype.sort

Array.prototype.sort

Array.prototype.sort is a method that can be accessed on arrays in JavaScript that can sort the array based on the callback provided.

It uses the "in-place" sorting algorithm.

The callback passed into the method must accept two arguments which will be two different items within the array.

Then within the callback the items can be arranged based on some custom conditions.

The callback must return one of three numbers for each time it is called (for each iteration), 0, greater than 0 or less than 0 (these numbers can be seen as 1, 0 or -1).

This means that in the callback function f(a, b) where a and b are array items:

  • Returning 1 will place a after b.
  • Returning 0 will leave the order unchanged.
  • Returning -1 will place b after a.

When sorting through an array of numbers the same result can be taken by subtracting one number from the other because this will result in the same result.

0 will be for matching numbers, and for greater than 0 results it will be moved to the next item, and less than 0 results will be moved to the previous item.

Inverting the calculation will invert the order of the array.

Related topics

© 2024 MWXYZ