The internal implementation of v8 is not discussed here.
const arr = [1, 35, 12, 151, 12, 1, 2, 1, 1, 15, 2, 123, 33, 1252, 36, 326]
arr.sort((a, b) => a - b)
console.log(arr)
// The result is sorted in ascending order
The sort
method, as described in the documentation, can quickly sort numbers in ascending or descending order. However, what if we want to sort in a hierarchical order?
Hierarchical Sorting
For now, let's focus on dividing the data into two layers, splitting the data into two parts while preserving the original order. The use case here is that the data has already been sorted as required previously, but now we need to prioritize sorting based on certain conditions.
This type of sorting can easily be achieved by splitting the array and then concatenating it, which can be done with a single traversal. However, using sort
is more concise and convenient.
Conclusion
If you refer to the MDN documentation for the compareFn
, it can be somewhat confusing. So, let's jump straight to the code conclusion:
const arr = [1, 35, 12, 'a', 151, 12, 1, 2, 1, 'b', 'c', 'd']
arr.sort((b, a) => {
return typeof a === 'string' && typeof b === 'number' ? -1 : 0
})
console.log(arr)
// [1, 35, 12, 151, 12, 1, 2, 1, 'a', 'b', 'c', 'd']
The goal here is to place numbers before strings while preserving the original order. Here are the key points to note:
- The
compareFn
returns-1
to indicate thata
andb
should be swapped. - The
compareFn
is defined as(b, a) => number
, which reverses the order ofa
andb
.- This is because if we think of the original array as
[a, b, c, d]
, passing(b, a)
makes more sense in this context.
- This is because if we think of the original array as
- Returning
1
or0
will both preserve the order, but1
means that each element is considered to be after the other elements.- Therefore, for consistency between the code and its meaning, returning
0
is preferable.
- Therefore, for consistency between the code and its meaning, returning