The sort() method sorts array elements in-place. By default, sort() converts elements to strings and compares their UTF-16 code unit values, which produces unexpected sorting order for numbers unless a custom comparator function is provided.
flowchart TD
SortCall["arr.sort(comparator)"] --> HasComp{"Is comparator function provided?"}
HasComp -- "No Comparator" --> StringSort["Converts elements to Strings & compares lexicographically ('10' < '2')"]
HasComp -- "Comparator (a, b)" --> CompLogic{"Evaluates (a, b)"}
CompLogic -- "< 0" --> AFirst["a comes before b"]
CompLogic -- "> 0" --> BFirst["b comes before a"]
CompLogic -- "=== 0" --> KeepOrder["Original relative order preserved"]
| Method | Mutates Original? | Return Value | Description |
|---|---|---|---|
sort(compareFn) |
Yes | Mutated original array | Sorts elements in-place. |
reverse() |
Yes | Mutated original array | Reverses elements in-place. |
toSorted(compareFn) |
No | New sorted array copy | Non-mutating ES2023 sorted copy. |
toReversed() |
No | New reversed array copy | Non-mutating ES2023 reversed copy. |
// Demonstrating default sorting traps, comparator logic, and non-mutating toSorted
// 1. Default String Sorting Trap on Numbers
const numbers = [10, 5, 40, 25, 100, 1];
const defaultSorted = [...numbers].sort();
console.log("Default Sort (String Lexicographical Trap):", defaultSorted);
// Output: [1, 10, 100, 25, 40, 5] (Incorrect for numeric values!)
// 2. Numeric Sorting with Custom Comparator (a - b)
const numericAscending = [...numbers].sort((a, b) => a - b);
console.log("Numeric Ascending Sort:", numericAscending); // [1, 5, 10, 25, 40, 100]
const numericDescending = [...numbers].sort((a, b) => b - a);
console.log("Numeric Descending Sort:", numericDescending); // [100, 40, 25, 10, 5, 1]
// 3. Sorting Array of Objects by Property
const inventory = [
{ name: "Laptop", price: 1200 },
{ name: "Mouse", price: 25 },
{ name: "Monitor", price: 300 }
];
inventory.sort((a, b) => a.price - b.price);
console.log("Inventory sorted by price:", inventory);
// 4. Non-Mutating ES2023 toSorted()
const originalList = ["Banana", "Apple", "Cherry"];
const sortedCopy = originalList.toSorted();
console.log("Original Array (Unchanged):", originalList);
console.log("Sorted Copy:", sortedCopy);
.sort() on arrays of numbers without (a, b) => a - b.toSorted() in Immutable Architectures: Use ES2023 toSorted() to avoid mutating input props or state arrays in frameworks like React.a.localeCompare(b) inside your comparator function.Write a custom comparator function to sort an array of string names alphabetically, taking accented characters (e.g. "Álvaro", "Zoe") into account properly.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.