Course

JavaScript Sort: Sorting Arrays in JavaScript

Sorting arrays in JavaScript is simple and versatile with the sort() method. This method allows you to sort arrays of numbers, strings, or objects with custom functions.

How to Use the JavaScript sort() Method

The sort() method sorts the elements of an array in-place and and returns the reference to the same array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values.

jsx
array.sort(compareFunction)
  • array: The original array you want to sort using the sort() method.
  • compareFunction (optional): A function defining the sort order. If omitted, elements are converted to strings and sorted based on their UTF-16 code units.

Default Sorting

Without a custom compare function, sort() converts elements to strings and sorts them alphabetically.

jsx
const fruits = ['banana', 'apple', 'cherry']; fruits.sort(); console.log(fruits); // Outputs: ['apple', 'banana', 'cherry']

Custom Sorting Function

With a compare function, you can specify custom sorting behavior. For example, sorting numbers in ascending or descending order:

jsx
const numbers = [4, 2, 9, 1]; numbers.sort((a, b) => a - b); // Ascending console.log(numbers); // Outputs: [1, 2, 4, 9] numbers.sort((a, b) => b - a); // Descending console.log(numbers); // Outputs: [9, 4, 2, 1]

The return value of the compareFunction determines the order: a negative value places a before b, while a positive value does the opposite.

When to Use sort() in JavaScript

The sort() method is helpful whenever you need an ordered collection. From simple arrays of numbers and strings to more complex objects, sort() is an essential tool for array methods.

Sorting Numbers

When sorting numbers, always use a compare function to ensure numerical comparison.

jsx
const scores = [20, 100, 40, 10]; scores.sort((a, b) => a - b); // Sorts scores in ascending order console.log(scores); // Outputs: [10, 20, 40, 100]

Sorting Alphabetically

You can use sort() to sort strings alphabetically, ideal for lists of names or other textual data.

jsx
const names = ["Anna", "John", "Charles", "Bill"]; names.sort(); console.log(names); // Outputs: ['Anna', 'Bill', 'Charles', 'John']

Sorting Arrays with JSON Data

The sort() method is frequently used with JSON data, especially when working with APIs.

jsx
const data = [ { id: 3, value: "C" }, { id: 1, value: "A" }, { id: 2, value: "B" } ]; data.sort((a, b) => a.id - b.id); // Sorts by ID console.log(data); // Outputs: [{ id: 1, value: "A" }, { id: 2, value: "B" }, { id: 3, value

Sorting Objects by Property

For arrays of objects, the sort() method lets you sort by specific properties.

jsx
const users = [ { name: "Alice", age: 25 }, { name: "Bob", age: 30 }, { name: "Charlie", age: 20 } ]; users.sort((a, b) => a.age - b.age); // Sorts users by age console.log(users); // Outputs: [{ name: "Charlie", age: 20 }, { name: "Alice", age: 25 }, { name: "Bob", age: 30 }]

Examples of Sorting Arrays in JavaScript

Sorting Strings Alphabetically

Many applications rely on sorting strings alphabetically, such as search engines or online catalogs.

jsx
const cities = ["Paris", "New York", "London", "Tokyo"]; cities.sort(); console.log(cities); // Outputs: ['London', 'New York', 'Paris', 'Tokyo']

Sorting Dates

Calendar and scheduling applications often sort dates to present events in chronological order.

jsx
const dates = [new Date(2023, 11, 15), new Date(2022, 5, 18), new Date(2023, 3, 25)]; dates.sort((a, b) => a - b); // Sorts dates in ascending order console.log(dates); // Outputs dates sorted by year and month

Sorting Objects by Multiple Properties

Complex data like user profiles or product listings might require sorting by several properties.

jsx
const products = [ { name: "Laptop", price: 1000 }, { name: "Phone", price: 800 }, { name: "Tablet", price: 600 } ]; products.sort((a, b) => a.price - b.price); // Sorts products by price console.log(products); // Outputs products sorted by price in ascending order

Learn More About Sorting in JavaScript

Sorting Arrays of Strings in JavaScript

You can also sort arrays of strings alphabetically using the sort() method with default or custom compare functions, such as for case-insensitive sorting.

jsx
const animals = ["Zebra", "antelope", "Lion", "giraffe"]; animals.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); console.log(animals); // Outputs: ['antelope', 'giraffe', 'Lion', 'Zebra']

JavaScript Sorting Arrays of Objects

For more advanced sorting, such as sorting objects by multiple properties, you can chain multiple comparison logic.

jsx
const library = [ { title: "Book A", year: 2010 }, { title: "Book B", year: 2005 }, { title: "Book A", year: 2005 } ]; library.sort((a, b) => { if (a.title === b.title) return a.year - b.year; return a.title.localeCompare(b.title); }); console.log(library); // Outputs library sorted by title and then by year

JavaScript Sorting Strings Alphabetically

For case-sensitive sorting of strings, the default sort() method behavior is enough. However, for case-insensitive sorting, a custom compare function ensures accurate results.

jsx
const colors = ["Blue", "red", "green", "Yellow"]; colors.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); console.log(colors); // Outputs: ['Blue', 'green', 'red', 'Yellow']

Performance Considerations for JavaScript Sorting

While sort() is efficient for many use cases, large arrays might benefit from optimized sorting algorithms. JavaScript engines use different algorithms internally, but understanding their complexity helps optimize performance.

jsx
const largeArray = new Array(10000).fill(0).map(() => Math.random()); largeArray.sort((a, b) => a - b); // Efficient sorting for large arrays

Advanced Sorting with JavaScript Map and Set

Using ES6 Map and Set with sort() helps manage collections with unique keys or values, simplifying complex data manipulation.

jsx
const set = new Set([3, 1, 4, 1, 5, 9]); const sortedSet = Array.from(set).sort((a, b) => a - b); console.log(sortedSet); // Outputs: [1, 3, 4, 5, 9]

Sorting Arrays with map() and Custom Comparators

For intricate sorting requirements, combining sort() with map() and custom comparators helps maintain clean and readable code.

jsx
const personnel = [ { name: "Alice", role: "Developer" }, { name: "Bob", role: "Designer" }, { name: "Eve", role: "Developer" } ]; personnel.sort((a, b) => a.role.localeCompare(b.role) || a.name.localeCompare(b.name)); console.log(personnel); // Outputs sorted personnel by role and name

Ready to learn more? Check out our front-end-development course for beginner-friendly JavaScript, React, CSS and HTML tutorials.