Preface
In JavaScript,sort
Methods are an important part of array objects. It provides a simple and powerful way to sort arrays. This article will introduce in detailsort
The basic concepts, usage, common application scenarios, comparisons with other sorting methods, and provide practical examples to help you fully master this powerful tool.
1. Basic concepts of sort method
sort
Methods are used to sort array elements and return the sorted array. By default,sort
The method is sorted by string Unicode code points. This means that if the array elements are numbers, they will be sorted in character order, not numeric order. Therefore, when sorting arrays of numbers, it is often necessary to provide a comparison function.
grammar:
([compareFunction])
compareFunction (optional): Function used to define the sort order. If this parameter is omitted, the array elements will be sorted by string Unicode code points.
2. Basic usage examples
Here is a simple example, usingsort
Methods sort string arrays:
const fruits = ['banana', 'apple', 'cherry']; (); (fruits);
// Output: ['apple', 'banana', 'cherry']
In this example,sort
Methods are alphabeticalfruits
Arrays for sorting.
3. Numerical sorting
Since the default sorting method sorts numbers in character order, a comparison function needs to be provided when sorting a numeric array. The comparison function takes two parameters and returns a numeric value:
- If the return value is less than 0,
a
Will be rankedb
Before. - If the return value is equal to 0,
a
andb
The relative order remains the same. - If the return value is greater than 0,
a
Will be rankedb
after.
Example: Ascending order sort
const numbers = [10, 5, 20, 3]; ((a, b) => a - b); (numbers);
// Output: [3, 5, 10, 20]
In this example, the comparison function isa - b
make surenumbers
Arrays are sorted in ascending order.
Example: Sort in descending order
((a, b) => b - a); (numbers);
// Output: [20, 10, 5, 3]
In this example, the comparison function isb - a
make surenumbers
Arrays are sorted in descending order.
4. Ordering of object arrays
In actual development, it is often necessary to sort object arrays. The array can be sorted based on a certain property of the object by providing a comparison function.
Example: Sort by object properties
const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 20 } ]; ((a, b) => - ); (users);
// Output:
// [
// { name: 'Charlie', age: 20 },
// { name: 'Alice', age: 25 },
// { name: 'Bob', age: 30 }
// ]
In this example, the comparison function is -
make sureusers
Array pressage
Attributes sort in ascending order.
5. Handle special circumstances
Handle case-insensitive sorting
The default string sort is case sensitive. If you need to do case-insensitive sorting, you can use it in the comparison functiontoLowerCase
method.
const fruits = ['banana', 'Apple', 'cherry']; ((a, b) => ().localeCompare(())); (fruits);
// Output: ['Apple', 'banana', 'cherry']
Processing containsundefined
Array of
In order, containsundefined
When an array ofundefined
Treat as the maximum or minimum value, place it at the end or beginning of the array by comparing functions.
const arr = [3, undefined, 1, 2]; ((a, b) => { if (a === undefined) return 1; if (b === undefined) return -1; return a - b; }); (arr);
// Output: [1, 2, 3, undefined]
6. Comparison with other sorting methods
sort
Compared with other sorting methods (such as manually implemented sorting algorithms), the method has the advantages of simplicity and efficiency. Although manually implementing sorting algorithms (such as bubble sorting, quick sorting) can better understand the sorting principle, in actual development, the built-insort
The method is usually easier and more efficient.
Bubble sorting example
function bubbleSort(arr) { for (let i = 0; i < ; i++) { for (let j = 0; j < - i - 1; j++) { if (arr[j] > arr[j + 1]) { [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; } } } return arr; } const numbers = [5, 3, 8, 4, 2]; (bubbleSort(numbers));
// Output: [2, 3, 4, 5, 8]
Although this manually implemented bubble sort can complete the sorting task, it is related to the built-insort
Compared with the method, it has more code volume and less efficient code.
7. Practical examples
Example 1: Sort students' names alphabetically
Suppose we have an array containing student names that need to be sorted alphabetically:
const students = ['John', 'Anna', 'Zara', 'Bob']; (); (students);
// Output: ['Anna', 'Bob', 'John', 'Zara']
Example 2: Sort student object array by score
Suppose we have an array containing student objects that need to be sorted by scores:
const students = [ { name: 'John', score: 85 }, { name: 'Anna', score: 92 }, { name: 'Zara', score: 74 }, { name: 'Bob', score: 89 } ]; ((a, b) => - ); (students);
// Output:
// [
// { name: 'Anna', score: 92 },
// { name: 'Bob', score: 89 },
// { name: 'John', score: 85 },
// { name: 'Zara', score: 74 }
// ]
Example 3: Sort by date
Suppose we have an array containing date strings that need to be sorted by date:
const dates = ['2023-03-15', '2021-06-01', '2022-12-25']; ((a, b) => new Date(a) - new Date(b)); (dates);
// Output: ['2021-06-01', '2022-12-25', '2023-03-15']
8. Precautions and best practices
Consistency of array element types
Ensure that the elements in the array are consistent, otherwise the sorting results may not be as expected.
const mixed = [1, '2', 3, '10']; (); (mixed);
// Output: [1, '10', 3, '2']
Use stable sorting
Defaultsort
The method is stable, i.e., for equal elements, their relative order remains the same. This is very important for certain scenarios (such as quadratic sorting).
Pay attention to performance
When processing large arrays,sort
The performance of the method may become a bottleneck. Although the V8 engine issort
The method is optimized, but in extreme cases, consider using a more efficient sorting algorithm or a strategy of dividing and conquering.
This is the end of this article about the detailed explanation of JavaScript sort sorting example. For more related JavaScript sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!