Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Sorting Arrays with sort | Advanced Array Manipulation
JavaScript Array Methods

bookSorting Arrays with sort

Sorting arrays in JavaScript can appear straightforward, but the sort method has some behaviors that often surprise new users. By default, sort converts array elements to strings and compares their sequences of UTF-16 code units, which can lead to unexpected results, especially with numbers. For example, sorting [10, 2, 30] without any additional arguments will not yield a numerically ordered array. This is why custom comparator functions are frequently necessary—to achieve predictable, logical orderings for numbers or more complex data structures.

1234567891011121314
const numbers = [10, 2, 30, 1]; // Default sort (lexicographical) const defaultSorted = [...numbers].sort(); // [1, 10, 2, 30] // Ascending numeric sort const ascending = [...numbers].sort((a, b) => a - b); // [1, 2, 10, 30] // Descending numeric sort const descending = [...numbers].sort((a, b) => b - a); // [30, 10, 2, 1] console.log('Default:', defaultSorted); console.log('Ascending:', ascending); console.log('Descending:', descending);
copy

When you want to sort an array of objects, such as a list of users by their age property, you must provide a comparator function that compares those specific properties. The comparator receives two elements at a time and should return a negative number if the first element should come before the second, a positive number if it should come after, or zero if they are equal. This approach gives you full control over the sorting logic, whether you're sorting numbers, strings, or custom objects.

The sort method is mutable: it changes the array it is called on, rather than returning a new sorted array. This means that after sorting, the original array's order is altered. If you need to preserve the original order, you should first make a copy with slice or the spread operator before sorting.

Note

Sorting arrays of strings with sort works for basic cases, but may not handle locale-specific characters or case sensitivity as you expect. For more robust string sorting, use localeCompare inside your comparator function, like (a, b) => a.localeCompare(b).

1. Which of the following best describes the result of using array.sort() on [3, 12, 7, 100] without a comparator function?

2. Complete the comparator function so that the people array is sorted by the age property in ascending order.

question mark

Which of the following best describes the result of using array.sort() on [3, 12, 7, 100] without a comparator function?

Select the correct answer

question-icon

Complete the comparator function so that the people array is sorted by the age property in ascending order.

people.sort((a, b) => );
[{"name":"Bob","age":25},{"name":"Alice","age":30},{"name":"Carol","age":35}]

Click or drag`n`drop items and fill in the blanks

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 1

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Awesome!

Completion rate improved to 8.33

bookSorting Arrays with sort

Sveip for å vise menyen

Sorting arrays in JavaScript can appear straightforward, but the sort method has some behaviors that often surprise new users. By default, sort converts array elements to strings and compares their sequences of UTF-16 code units, which can lead to unexpected results, especially with numbers. For example, sorting [10, 2, 30] without any additional arguments will not yield a numerically ordered array. This is why custom comparator functions are frequently necessary—to achieve predictable, logical orderings for numbers or more complex data structures.

1234567891011121314
const numbers = [10, 2, 30, 1]; // Default sort (lexicographical) const defaultSorted = [...numbers].sort(); // [1, 10, 2, 30] // Ascending numeric sort const ascending = [...numbers].sort((a, b) => a - b); // [1, 2, 10, 30] // Descending numeric sort const descending = [...numbers].sort((a, b) => b - a); // [30, 10, 2, 1] console.log('Default:', defaultSorted); console.log('Ascending:', ascending); console.log('Descending:', descending);
copy

When you want to sort an array of objects, such as a list of users by their age property, you must provide a comparator function that compares those specific properties. The comparator receives two elements at a time and should return a negative number if the first element should come before the second, a positive number if it should come after, or zero if they are equal. This approach gives you full control over the sorting logic, whether you're sorting numbers, strings, or custom objects.

The sort method is mutable: it changes the array it is called on, rather than returning a new sorted array. This means that after sorting, the original array's order is altered. If you need to preserve the original order, you should first make a copy with slice or the spread operator before sorting.

Note

Sorting arrays of strings with sort works for basic cases, but may not handle locale-specific characters or case sensitivity as you expect. For more robust string sorting, use localeCompare inside your comparator function, like (a, b) => a.localeCompare(b).

1. Which of the following best describes the result of using array.sort() on [3, 12, 7, 100] without a comparator function?

2. Complete the comparator function so that the people array is sorted by the age property in ascending order.

question mark

Which of the following best describes the result of using array.sort() on [3, 12, 7, 100] without a comparator function?

Select the correct answer

question-icon

Complete the comparator function so that the people array is sorted by the age property in ascending order.

people.sort((a, b) => );
[{"name":"Bob","age":25},{"name":"Alice","age":30},{"name":"Carol","age":35}]

Click or drag`n`drop items and fill in the blanks

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 1
some-alt