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. If you are building lists that later need merging or cleanup, JavaScript unique array is a related topic.
Tested On: The examples were tested with Node.js v20.18.1 on a Linux system. The same sort behavior works in modern browsers and JavaScript runtimes.
Default sort() uses string comparison
const mixed = [10, 2, 5, 1, 3];
mixed.sort();
console.log("sorted-default:", mixed.join(","));Tested output:
sorted-default: 1,10,2,3,5Use a compare function (below) for arbitrary numbers, or toSorted() when you need a sorted copy without mutating the original array.
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(","));Tested output:
sorted-words: apple,banana,cherrySort 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(","));Tested output:
sorted-numbers: 1,2,3,4,5Use a - b for ascending order and b - a for descending order.
Sort objects by property
Compare the object property you want to order by.
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(" | "));Tested output:
sorted-books: Pride and Prejudice | The Great Gatsby | To Kill a MockingbirdThis 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.
