Phương pháp sắp xếp mảng trong ES6 cùng các hàm so sánh thực tế
Phương thức Array.prototype.sort() trong ES6 cho phép sắp xếp mảng trực tiếp với cú pháp ngắn gọn và linh hoạt. Dưới đây là các ví dụ minh họa cách sử dụng hiệu quả.
// Sắp xếp mảng số tăng dần
const digits = [7, 1, 4, 3, 9];
digits.sort((x, y) => x - y);
console.log(digits); // [1, 3, 4, 7, 9]
Hàm so sánh nhận hai tham số x và y, trả về giá trị âm nếu x cần đứng trước y, dương nếu ngược lại.
Sắp xếp chuỗi theo độ dài
// Sắp xếp mảng chuỗi theo chiều dài
const items = ['mango', 'pear', 'kiwi', 'grape'];
items.sort((a, b) => a.length - b.length);
console.log(items); // ["kiwi", "pear", "mango", "grape"]
Sắp xếp mảng đối tượng
// Sắp xếp theo tuổi tăng dần
const users = [
{ fullName: 'Eva', year: 28 },
{ fullName: 'Liam', year: 22 },
{ fullName: 'Noah', year: 31 }
];
users.sort((p1, p2) => p1.year - p2.year);
console.log(users);
// Kết quả: [{fullName: 'Liam', year: 22}, {fullName: 'Eva', year: 28}, {fullName: 'Noah', year: 31}]
Xử lý trường hợp đặc biệt
// Sắp xếp mảng có giá trị null/undefined
const combinedData = [5, null, 2, undefined, 4, null];
combinedData.sort((m, n) => {
if (m === null || m === undefined) return 1;
if (n === null || n === undefined) return -1;
return m - n;
});
console.log(combinedData); // [2, 4, 5, null, undefined, null]
Tiếp cận thực tế
- Sắp xếp giảm dần:
numbers.sort((a, b) => b - a) - Chuỗi không phân biệt hoa thường:
words.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); - Sắp xếp ngày tháng:
dates.sort((d1, d2) => new Date(d1) - new Date(d2));
Tối ưu hiệu suất
// Tạo mảng mới thay vì thay đổi mảng gốc
const sortedDigits = Array.from(digits).sort((x, y) => x - y);
// Lọc và sắp xếp đồng thời
const processedData = bigData
.filter(item => item !== null)
.sort((a, b) => a.value - b.value);
Tối ưu hóa hàm so sánh
// Tính toán khóa sắp xếp trước
const entries = [/* dữ liệu lớn */];
const entriesWithKeys = entries.map(entry => ({
...entry,
sortKey: calculateSortKey(entry) // Hàm xử lý phức tạp
}));
entriesWithKeys.sort((a, b) => a.sortKey - b.sortKey);