Sort an Array in JavaScript with sort()

Tech reviewed: Deepak Prasad
Sort an Array in JavaScript with sort()

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

javascript
const mixed = [10, 2, 5, 1, 3];
mixed.sort();
console.log("sorted-default:", mixed.join(","));

Tested output:

text
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.


Sort strings with default sort()

For an array of strings, UTF-16 lexicographic order is usually what you want, and default sort() is enough.

javascript
const words = ["banana", "apple", "cherry"];
words.sort();
console.log("sorted-words:", words.join(","));

Tested output:

text
sorted-words: apple,banana,cherry

Sort numbers with a compare function

A numeric compare function prevents string-based ordering.

javascript
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log("sorted-numbers:", numbers.join(","));

Tested output:

text
sorted-numbers: 1,2,3,4,5

Use a - b for ascending order and b - a for descending order.


Sort objects by property

Compare the object property you want to order by.

javascript
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:

text
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.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital …

  • JavaScript
  • Web Design