How JavaScript #Array.sort method works internally?

JavaScript Array.sort works in three phases pre-processing, sorting and post-processing.

A. Pre-processing

  • Calculates/ counts undefined values.
  • Creates a temporary array with actual values.

B. Sorting

  • In this phase actual sorting is done on the temporary array.

C. Post-processing

  • After sorting is done the sorted values written back to the original array.
  • Final sorted array contains a temporary array with sorted elements and undefined values which are counted in pre-processing.

The pre-processing algorithm looks like below:

  1. Let length be the value of "length" property of an array/obect.
  2. Let numberOfUndefined be 0.
  3. For each value in the range [0, length]
    • If value is a hole: do nothing
    • If value is undefined: Increment numberOfUndefined by 1
    • Otherwise add value to temporary list elements

The post-processing algorithm looks like below:

  1. Write back all values from temporary list to the original array/object in the range [0, elements.length]
  2. Set all values from [elements.length, elements.length + numberOfUndefined] to undefined.
  3. Delete all values in the range from [elements.length + numberOfUndefined, length].