JS: Array.prototype.sort

By Xah Lee. Date: . Last updated: .

Sort myArray.

The array is modified.

Elements are converted to string for comparison.

Return the modified array.

f is a ordering function. The function should take 2 arguments x y, and return:

myArray can be a array-like object.

[see JS: Array-Like Object]

WARNING: by spec, sort is not necessarily stable. That is, elements that are considered equal in order may be moved from the order they were in the original array.

// array sort example

const aa = ["a1", "a70", "a8", "A2"];

console.log (
    // default sort. element compared as string
// [ 'A2', 'a1', 'a70', 'a8' ]

// the array is modified
console.log(aa); // [ 'A2', 'a1', 'a70', 'a8' ]

Custom Order Function

Sorting array using custom order function:

// array sort using custom function

// custom ordering function
const ff = ((x, y) => {
    // x and y are strings. we remove first char. consider rest as number
    const nx = parseInt(x.slice(1));
    const ny = parseInt(y.slice(1));

    if ( nx < ny ) { return -1; }
    if ( nx > ny ) { return 1; }
    if ( nx == ny ) { return 0; }

// sort by comparing as numbers after first char

console.log (
    ["a1", "a70", "a8", "A2"].sort(ff)
// [ 'a1', 'A2', 'a8', 'a70' ]

Default Order Function

If order function is not undefined, the default will convert each element to a string if necessary by calling toString() method, then compare by their code point units. (note: not characters unicode code point)

[see JS: String Code Unit vs Code Point]

Here's example showing it sorts by code unit and not code point.

// example showing default comparison function for string, sorts by code unit and not code point.

console.log ( ['﷽','😆'].sort());
// prints
// [ '😆', '﷽' ]

// 😆 (codepoint 128518, U+1f606)
// utf-16 encoding: #xFE #xFF #xD8 #x3D #xDE #x06

// ﷽ (codepoint 65021, U+fdfd)
 // utf-16 encoding: #xFE #xFF #xFD #xFD

Order Function Must be Consistent

Note: the custom order function must be consistent, else the result of sort is implementation dependent.

Consistent means, for any x y z in the array:

  1. f(x,x) === 0
  2. if f(x,y) === 0 and f(y,z) === 0 then f(x,z) === 0
  3. if f(x,y) === -1 and f(y,z) === -1 then f(x,z) === -1
  4. if f(x,y) === 1 and f(y,z) === 1 then f(x,z) === 1

The above guarantee that the set is partitioned into classes by a equivalence relation, and the equivalence classes are total ordered.

also, the following are required due to how JavaScript the language works:


ECMAScript® 2016 Language Specification#sec-array.prototype.sort

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth