Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức Array.prototype.sort() trong JavaScript

Tổng quan

Array.prototype.sort() sắp xếp các phần tử của mảng tại chỗ (in-place) và trả về mảng đã sắp xếp. Mặc định sắp xếp theo thứ tự chữ (Unicode), không phải số.

Cú pháp

arr.sort([compareFunction])

Ví dụ cơ bản

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array sort()</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
        .sample, .result { font-size: 16px; font-weight: 500; margin: 10px 0; padding: 10px; border-radius: 4px; }
        .sample { color: #d32f2f; background: #ffebee; }
        .result { color: #6a1b9a; background: #f3e5f5; }
        button { padding: 8px 16px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>JavaScript Array.prototype.sort() method</h1>
    <div class="sample" id="sample"></div>
    <div class="result" id="result"></div>
    <button id="btn">SẮP XẾP</button>
    <h3>Nhấn nút để sắp xếp mảng</h3>

    <script>
        const sampleEle = document.getElementById('sample');
        const resultEle = document.getElementById('result');
        const btn = document.getElementById('btn');

        const arr = [9, 1, 4, 2, 99, 11, 22];
        sampleEle.innerHTML = `Mảng gốc: [${arr}]`;

        btn.addEventListener('click', () => {
            // Sắp xếp mặc định (theo chuỗi) - KHÔNG ĐÚNG cho số
            resultEle.innerHTML = `Mảng đã sắp xếp (mặc định): [${arr.sort()}]`;
        });
    </script>
</body>
</html>

⚠️ Lưu ý quan trọng: Sắp xếp số

Mặc định sort() chuyển phần tử thành chuỗi so sánh, dẫn đến kết quả sai với số:

[9, 1, 4, 2, 99, 11, 22].sort() 
// Kết quả: [1, 11, 2, 22, 4, 9, 99] ❌ (theo chữ)

Sắp xếp số đúng cách

// Tăng dần
arr.sort((a, b) => a - b);
// [1, 2, 4, 9, 11, 22, 99] ✅

// Giảm dần
arr.sort((a, b) => b - a);
// [99, 22, 11, 9, 4, 2, 1] ✅

Sắp xếp đối tượng

const users = [
    { name: 'An', age: 25 },
    { name: 'Bình', age: 20 },
    { name: 'Cường', age: 30 }
];

// Sắp xếp theo tuổi tăng dần
users.sort((a, b) => a.age - b.age);

Sắp xếp chuỗi có dấu (tiếng Việt)

const fruits = ['Táo', 'Xoài', 'Bơ', 'Dưa'];
fruits.sort((a, b) => a.localeCompare(b, 'vi'));
// ['Bơ', 'Dưa', 'Táo', 'Xoài'] ✅

Kết quả ví dụ

Mảng gốc: [9, 1, 4, 2, 99, 11, 22]
Sắp xếp mặc định: [1, 11, 2, 22, 4, 9, 99] (sai về mặt số)
Sắp xếp số đúng: [1, 2, 4, 9, 11, 22, 99]