Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende 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

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 1

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Awesome!

Completion rate improved to 8.33

bookSorting Arrays with sort

Desliza para mostrar el menú

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

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 1
some-alt