Table of Contents

JavaScript Array sort() Method is a built-in method that arranges the elements of an array in a specific order. It is commonly used to sort numbers, names, dates, product lists, student records, and other collections of data. By default, JavaScript converts array elements to strings and compares their UTF-16 code unit sequences. This default behavior is suitable for many simple text arrays, but it does not produce correct numeric ordering in every situation.

Syntax of JavaScript sort() Method

array.sort()
array.sort(compareFunction)

The sort() method accepts one optional argument:

  • compareFunction: A function that defines the sorting order. It receives two elements, often named a and b, and returns a number that indicates their relative order.

If you omit the compare function, JavaScript converts the elements to strings and sorts them according to their UTF-16 code units. The method sorts the array in place, so the original array is modified.

Basic Example of sort() Method

You can use sort() without arguments to arrange an array of strings in its default order.

const fruits = ["Mango", "Apple", "Orange", "Banana"];

fruits.sort();

console.log(fruits);

Output:

["Apple", "Banana", "Mango", "Orange"]

In this example, JavaScript compares the string values and arranges them alphabetically for these simple English words. The original fruits array now contains the sorted order. The method also returns the array itself, so you can chain it with other array operations when appropriate.

Default Sorting Behavior

When no compare function is supplied, elements are converted to strings before comparison. This is why default sorting can be surprising when an array contains numbers.

const values = [4, 20, 100, 9, 30];

values.sort();

console.log(values);

Output:

[100, 20, 30, 4, 9]

The values are ordered by their string representations, not by their numeric magnitude. For example, the string representation of 100 begins with the character 1, so it can appear before 20. Use a numeric compare function whenever you need mathematical ordering.

Sorting Numbers in Ascending Order

To sort numbers from the smallest to the largest, pass a compare function that subtracts b from a.

const numbers = [40, 5, 100, 25, 10];

numbers.sort((a, b) => a - b);

console.log(numbers);

Output:

[5, 10, 25, 40, 100]

The expression a - b determines the order of each compared pair. If the result is negative, a is placed before b. If it is positive, a is placed after b. If the result is zero, the comparator treats the two values as equal for sorting purposes.

Sorting Numbers in Descending Order

To arrange numbers from largest to smallest, reverse the subtraction order and use b - a.

const numbers = [40, 5, 100, 25, 10];

numbers.sort((a, b) => b - a);

console.log(numbers);

Output:

[100, 40, 25, 10, 5]

This pattern is useful for sorting prices, marks, ratings, quantities, and scores when the highest value should appear first. The original array is rearranged in descending order.

Understanding the Compare Function

The compare function is the key to custom sorting. JavaScript calls it with two array elements and uses its numeric return value to determine their relative positions.

  • Negative result: Place a before b.
  • Positive result: Place a after b.
  • Zero: Treat a and b as equal for this comparison.
const numbers = [30, 10, 20];

numbers.sort((a, b) => {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
});

console.log(numbers);

Output:

[10, 20, 30]

A comparator does not have to return exactly -1 or 1; any negative or positive number communicates the direction. A reliable comparator should be consistent: comparing the same values should not produce contradictory ordering decisions.

Sorting an Array of Objects by a Numeric Property

Arrays often contain objects with multiple properties. You can sort these objects by selecting the property that should determine their order.

const students = [
    { name: "Rahim", age: 22 },
    { name: "Amina", age: 19 },
    { name: "Karim", age: 21 }
];

students.sort((a, b) => a.age - b.age);

console.log(students);

Output:

[
  { name: "Amina", age: 19 },
  { name: "Karim", age: 21 },
  { name: "Rahim", age: 22 }
]

The compare function reads the age property from both objects and subtracts the values. To sort by a different numeric property, replace age with that property name. This pattern is commonly used for student marks, product prices, employee salaries, and customer order totals.

Sorting an Array of Objects by a String Property

You can also sort objects by a text property such as a person’s name or a product title. Use localeCompare() to compare the selected values.

const products = [
    { name: "Laptop", price: 850 },
    { name: "Keyboard", price: 45 },
    { name: "Monitor", price: 220 }
];

products.sort((a, b) => a.name.localeCompare(b.name));

console.log(products);

The objects are arranged according to their name property, while all their other properties remain attached to the corresponding objects. Sorting objects does not separate their property values; it changes the order of the object references in the array.

Sorting by Multiple Properties

Sometimes one property is not enough to determine the desired order. You can compare a primary property first and use a secondary property when the primary values are equal.

const students = [
    { name: "Karim", grade: "A", age: 20 },
    { name: "Amina", grade: "A", age: 19 },
    { name: "Rahim", grade: "B", age: 21 }
];

students.sort((a, b) => {
    const gradeOrder = a.grade.localeCompare(b.grade);

    if (gradeOrder !== 0) {
        return gradeOrder;
    }

    return a.age - b.age;
});

console.log(students);

In this example, students are first sorted by grade. If two students have the same grade, their ages determine their relative order. This technique is useful for sorting records by department and name, products by category and price, or transactions by date and amount.

Sorting Without Changing the Original Array

The sort() method modifies the array on which it is called. If the original order must be preserved, create a shallow copy before sorting.

const numbers = [30, 10, 20];

const sortedNumbers = [...numbers].sort((a, b) => a - b);

console.log(sortedNumbers);
console.log(numbers);

Output:

[10, 20, 30]
[30, 10, 20]

The spread syntax creates a new array containing the same elements. The new array is sorted, while the original remains unchanged. This is especially useful when working with application state or when the unsorted data is needed elsewhere. Remember that this is a shallow copy: objects inside the array are still the same object references.

Using toSorted() for Non-Mutating Sorting

Modern JavaScript includes toSorted(), which returns a new sorted array without changing the original array. It accepts the same optional compare function as sort().

const numbers = [40, 10, 30, 20];

const sortedNumbers = numbers.toSorted((a, b) => a - b);

console.log(sortedNumbers);
console.log(numbers);

Output:

[10, 20, 30, 40]
[40, 10, 30, 20]

Choose toSorted() when you need an immutable sorting operation. If your application must support older browsers or runtimes, check compatibility or use the spread-and-sort approach instead.

Sorting Empty Slots and Undefined Values

When an array contains undefined values, JavaScript places them at the end during sorting. Empty slots in sparse arrays are also moved to the end, after undefined values. The compare function is not called for undefined elements.

const values = [3, undefined, 1, 2];

values.sort((a, b) => a - b);

console.log(values);

Output:

[1, 2, 3, undefined]

When your data may contain missing or null values, decide explicitly where those values should appear. A custom comparator can handle null values, while undefined values and empty slots follow the special behavior defined by the sort operation.