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:
- Let
length
be the value of"length"
property of an array/obect. - Let
numberOfUndefined
be 0. - For each
value
in the range[0, length]
- If value is a
hole
: do nothing - If value is
undefined
: IncrementnumberOfUndefined
by 1 - Otherwise add value to
temporary list
elements
- If value is a
The post-processing algorithm looks like below:
- Write back all values from
temporary list
to the original array/object in the range[0, elements.length]
- Set all values from
[elements.length, elements.length + numberOfUndefined]
toundefined
. - Delete all values in the range from
[elements.length + numberOfUndefined, length]
.