Зміст курсу
JavaScript Data Structures
JavaScript Data Structures
sort() Method
This chapter explores the intricacies of the sort()
method, including its syntax, default behaviors, and custom sorting techniques.
sort()
The sort()
method modifies the original array, imbuing it with a new arrangement.
Key characteristics to remember:
- The original array transforms, finding its elements in a new arrangement;
- The method furnishes a modified array as its return value, allowing for further exploration;
- By default, the sort() method arranges elements in ascending order.
Default Sorting Behavior
Default sorting unfolds seamlessly for arrays of strings, but numeric arrays might present challenges. Let's navigate through examples to illuminate this behavior:
const numbers = [51, 12, 43, 24, 65, 36]; numbers.sort(); console.log(numbers); // Output: 12, 24, 36, 43, 51, 65
In this example, the array of numbers is sorted in ascending order, seemingly straightforward. However, nuances emerge in the subsequent illustration:
const numbers = [34, 25, 19, 1, 92, 2, 3]; numbers.sort(); console.log(numbers); // Output: 1, 19, 2, 25, 3, 34, 92
The sort()
method treats elements as strings by default, which can lead to unexpected results. For instance, 19
is sorted before 2
, and 25
before 3
. The solution lies in customizing the sorting process.
Custom Sort Orders
To tailor sorting to specific needs, a callback function is employed. This function, often called a compare function, dictates the sorting logic. Let's explore custom sorting for both numbers and strings. Basic syntax:
a
is considered as the first element;b
is considered as the second element.
Sort Numbers
In this instance, the compare function dictates ascending and descending orders based on the relationship between elements a
and b
.
const numbers = [34, 25, 19, 1, 92, 2, 3]; const ascendingNumbers = [...numbers].sort((a, b) => a - b); console.log(ascendingNumbers); // Output: 1, 2, 3, 19, 25, 34, 92 const descendingNumbers = [...numbers].sort((a, b) => b - a); console.log(descendingNumbers); // Output: 92, 34, 25, 19, 3, 2, 1
Sort Strings
The localeCompare()
method facilitates alphabetical sorting, allowing customization for both ascending and descending orders.
const employees = ["Antonia", "Rene", "Casey", "Lorraine", "Shelia"]; const inAlphabetOrder = [...employees].sort((a, b) => a.localeCompare(b)); console.log(inAlphabetOrder); // Antonia, Casey, Lorraine, Rene, Shelia const inReversedOrder = [...employees].sort((a, b) => b.localeCompare(a)); console.log(inReversedOrder); // Shelia, Rene, Lorraine, Casey, Antonia
Дякуємо за ваш відгук!