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

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

Giới thiệu

Array.prototype.flat() (ES2019) tạo mảng mới bằng cách "làm phẳng" mảng lồng nhau theo độ sâu chỉ định. Không thay đổi mảng gốc.

Cú pháp

arr.flat([depth])
  • depth (tùy chọn): Độ sâu làm phẳng, mặc định là 1. Dùng Infinity để làm phẳng hoàn toàn.

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array flat()</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: #2e7d32; background: #e8f5e9; }
        button { padding: 8px 16px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Array.prototype.flat() method</h1>
    <div class="sample"><pre>[1, 2, 3, [4, 5], [6, [7, 8]]]</pre></div>
    <div class="result" id="result">Kết quả sau flat(1): <br></div>
    <button id="btn">LÀM PHẲNG (depth=1)</button>
    <h3>Nhấn nút để làm phẳng mảng với depth = 1</h3>

    <script>
        const resEle = document.getElementById('result');
        const btn = document.getElementById('btn');

        const arr = [1, 2, 3, [4, 5], [6, [7, 8]]];

        btn.addEventListener('click', () => {
            const flattened = arr.flat(1); // Chỉ làm phẳng 1 cấp
            resEle.innerHTML = 'Kết quả flat(1): <br>';
            flattened.forEach((item, index) => {
                resEle.innerHTML += `${index}: ${item}<br>`;
            });
            
            // Demo thêm depth=2 và Infinity
            resEle.innerHTML += '<br>flat(2): ' + JSON.stringify(arr.flat(2));
            resEle.innerHTML += '<br>flat(Infinity): ' + JSON.stringify(arr.flat(Infinity));
        });
    </script>
</body>
</html>

Kết quả

Mảng gốc: [1, 2, 3, [4, 5], [6, [7, 8]]]

  • flat(1): [1, 2, 3, 4, 5, 6, [7, 8]]
  • flat(2): [1, 2, 3, 4, 5, 6, 7, 8]
  • flat(Infinity): [1, 2, 3, 4, 5, 6, 7, 8]

Ứng dụng thực tế

// Gộp nhiều mảng kết quả từ API
const results = await Promise.all(requests);
const allData = results.flat();

// Loại bỏ các phần tử rỗng/undefined
const clean = arr.flat().filter(Boolean);

// Kết hợp với map (flatMap)
const sentences = ['Hello world', 'JavaScript is great'];
const words = sentences.flatMap(s => s.split(' '));
// ['Hello', 'world', 'JavaScript', 'is', 'great']

Hỗ trợ trình duyệt

Hỗ trợ tốt trên các trình duyệt hiện đại (Chrome 69+, Firefox 62+, Safari 12+, Edge 79+). Cần polyfill cho IE.