Knowledgize

.sort(fn)

The sort method in JavaScript is a versatile tool for ordering the elements of an array. Its default behavior is to sort elements as strings in ascending order, but it can be customized extensively using a comparison function. This allows for numeric sorting, sorting in descending order, sorting objects by properties, and handling special cases like case sensitivity and non-ASCII characters.


Syntax


array.sort([compareFunction])


Parameters


  • compareFunction (optional): A function that defines the sort order. If omitted, the array elements are converted to strings and sorted according to their UTF-16 code unit values.

Default Sorting Behavior


When no compareFunction is provided, the sort method sorts the array elements as strings in ascending order.



Example


const fruits = ['banana', 'apple', 'orange', 'mango']; fruits.sort(); console.log(fruits); // ['apple', 'banana', 'mango', 'orange']


Sorting with a Comparison Function


The compareFunction can be used to specify a different sort order. The function should return:

  • A negative value if the first argument should be sorted before the second.
  • Zero if the two arguments are considered equal.
  • A positive value if the first argument should be sorted after the second.


Example: Numeric Sorting


By default, numbers are sorted as strings, which can lead to incorrect results:


const numbers = [10, 2, 30, 4]; numbers.sort(); console.log(numbers); // [10, 2, 30, 4] (incorrect for numeric sort)

To sort numbers correctly, a comparison function is needed:


const numbers = [10, 2, 30, 4]; numbers.sort((a, b) => a - b); console.log(numbers); // [2, 4, 10, 30] (correct numeric sort)

Example: Sorting in Descending Order


You can reverse the order by switching the positions in the comparison function:


const numbers = [10, 2, 30, 4]; numbers.sort((a, b) => b - a); console.log(numbers); // [30, 10, 4, 2] (descending order)

Example: Sorting Objects by Property


When dealing with objects, you can sort based on a property of the objects.


const items = [ { name: 'apple', price: 30 }, { name: 'banana', price: 10 }, { name: 'orange', price: 20 } ]; items.sort((a, b) => a.price - b.price); console.log(items); // [{ name: 'banana', price: 10 }, { name: 'orange', price: 20 }, { name: 'apple', price: 30 }]

Stability of Sort


JavaScript’s sort function is not guaranteed to be stable. A stable sort preserves the relative order of records with equal keys. This behavior can differ between different JavaScript engines.


Performance Considerations

The time and space complexity of the sort method can vary depending on the JavaScript engine implementation, but it is generally O(n log n) for typical cases.


In-Place Sorting

The sort function modifies the original array, sorting it in place. This means that the original array is changed, and no new array is created.


Example


const array = [3, 1, 4, 1, 5, 9]; array.sort((a, b) => a - b); console.log(array); // [1, 1, 3, 4, 5, 9]

Special Considerations


  • Case Sensitivity: When sorting strings, the sort is case-sensitive by default. To achieve case-insensitive sorting, a custom comparison function is required.

    const words = ['banana', 'Apple', 'orange', 'Mango']; words.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); console.log(words); // ['Apple', 'banana', 'Mango', 'orange']
  • Non-ASCII Characters: For sorting strings with non-ASCII characters, localeCompare can be used for proper alphabetical order.

    const words = ['réservé', 'Premier', 'Cliché', 'communiqué']; words.sort((a, b) => a.localeCompare(b)); console.log(words); // ['Cliché', 'communiqué', 'Premier', 'réservé']