Sorting an array in JavaScript is a basic but important task when you want ordered data for display, comparison, or processing. The built-in sort() method can sort strings, numbers, and objects with a compare function.
For numeric data, the compare function matters because the default sort compares strings.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Default sort() uses string comparison
const mixed = [10, 2, 5, 1, 3];
mixed.sort();
console.log("sorted-default:", mixed.join(","));You should see one line logging sorted-default: 1,10,2,3,5.
Use a compare function (below) for arbitrary numbers, or toSorted() when you need a sorted copy without mutating the original array. When toSorted() is unavailable, copy with spread ([...arr]) before sort(); the spread operator covers shallow array copies.
Sort strings with default sort()
For an array of strings, UTF-16 lexicographic order is usually what you want, and default sort() is enough.
const words = ["banana", "apple", "cherry"];
words.sort();
console.log("sorted-words:", words.join(","));You should see one line logging sorted-words: apple,banana,cherry.
Sort numbers with a compare function
A numeric compare function prevents string-based ordering.
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log("sorted-numbers:", numbers.join(","));You should see one line logging sorted-numbers: 1,2,3,4,5.
Use a - b for ascending order and b - a for descending order.
ISO date strings and Date objects use the same compare-function pattern with timestamp subtraction—see JavaScript sort by date for ascending and descending examples.
Sort objects by property
Compare the object property you want to order by. String fields usually call localeCompare inside the compare function; see compare strings in JavaScript for locale and case-insensitive options.
const books = [
{ title: "The Great Gatsby" },
{ title: "To Kill a Mockingbird" },
{ title: "Pride and Prejudice" },
];
books.sort((a, b) => a.title.localeCompare(b.title));
console.log("sorted-books:", books.map((book) => book.title).join(" | "));You should see one line logging sorted-books: Pride and Prejudice | The Great Gatsby | To Kill a Mockingbird.
This is the pattern you use for structured data like tables, menus, and API records.
Summary
To sort an array in JavaScript, remember that default sort() compares string representations — fine for words, wrong for arbitrary numbers. Use a compare function for numeric order and localeCompare (or similar) for object properties. toSorted() is available when you need a new array without mutating the original.
