Sắp xếp mảng JavaScript()
Ví dụ
// Create an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Sort the Array
fruits.sort();
Hãy tự mình thử »Thêm ví dụ dưới đây!
Sự miêu tả
Phương thức sort()
sắp xếp các phần tử của một mảng.
Phương thức sort()
sắp xếp các phần tử dưới dạng chuỗi theo thứ tự bảng chữ cái và tăng dần.
Phương thức sort()
ghi đè lên mảng ban đầu.
Xem thêm:
Chức năng so sánh sắp xếp
Việc sắp xếp theo thứ tự bảng chữ cái có tác dụng tốt đối với các chuỗi ("Apple" đứng trước "Banana").
Tuy nhiên, việc sắp xếp số có thể tạo ra kết quả không chính xác.
"25" lớn hơn "100" vì "2" lớn hơn "1".
Bạn có thể khắc phục điều này bằng cách cung cấp "hàm so sánh" (Xem ví dụ bên dưới).
Cú pháp
array .sort( compareFunction )
Thông số
Parameter | Description |
compareFunction |
Optional. A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments:
When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. Example: The sort function will sort 40 as a value lower than 100. When comparing 40 and 100, sort() calls the function(40,100). The function calculates 40-100, and returns -60 (a negative value). |
Giá trị trả về
Kiểu | Sự miêu tả |
Mảng | Mảng với các mục được sắp xếp. |
Thêm ví dụ
Sắp xếp giảm dần
Sắp xếp rồi đảo ngược thứ tự:
// Create an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Sort the Array
fruits.sort();
// Reverse the array
fruits.reverse();
Hãy tự mình thử »Sắp xếp số
Sử dụng chức năng sắp xếp
Sắp xếp số theo thứ tự tăng dần:
// Create an Array
const points = [40, 100, 1, 5, 25, 10];
// Sort the Array
points.sort(function(a, b){return a-b});
Hãy tự mình thử »Sắp xếp số theo thứ tự giảm dần:
// Create an Array
const points = [40, 100, 1, 5, 25, 10];
// Sort the Array
points.sort(function(a, b){return b-a});
Hãy tự mình thử »Tìm giá trị thấp nhất:
// Create an Array
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order
points.sort(function(a, b){return a-b});
let lowest = points[0];
Hãy tự mình thử »Tìm giá trị cao nhất:
// Create an Array
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in descending order:
points.sort(function(a, b){return b-a});
let highest = points[0];
Hãy tự mình thử »Tìm giá trị cao nhất:
// Create an Array
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order:
points.sort(function(a, b){return a-b});
let highest = points[points.length-1];
Hãy tự mình thử »Hướng dẫn mảng:
Hỗ trợ trình duyệt
sort()
là một tính năng của ECMAScript1 (ES1).
ES1 (JavaScript 1997) được hỗ trợ đầy đủ trên tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |