Làm phẳng mảng lồng nhau với Array.flat()
Array.flat() (ES2019) tạo mảng mới với tất cả phần tử mảng con được ghép nối đệ quy đến độ sâu (depth) chỉ định. Mặc định depth = 1.
Cú pháp
arr.flat([depth])
depth(tùy chọn): Số nguyên ≥ 0. Mặc định = 1. DùngInfinityđể 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", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 18px; font-weight: 500; font-family: monospace; }
.result { color: green; }
button { padding: 8px 16px; cursor: pointer; }
pre { background: #f5f5f5; padding: 10px; border-radius: 4px; }
</style>
</head>
<body>
<h1>Array.flat() method</h1>
<div class="sample"><pre>[1, 2, 3, [4, 5], [6, [7, 8]]]</pre></div>
<div class="result">Sau flat(1): <br></div>
<button class="btn-demo">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.querySelector(".result");
const sampleEle = document.querySelector(".sample");
const btn = document.querySelector(".btn-demo");
const arr = [1, 2, 3, [4, 5], [6, [7, 8]]];
btn.addEventListener("click", () => {
// flat(1) chỉ làm phẳng 1 cấp
const flattened = arr.flat(1);
resEle.innerHTML = "Sau flat(1): <br>";
flattened.forEach((item, index) => {
resEle.innerHTML += index + ' : ' + item + ' ';
});
// Thêm demo depth 2 và Infinity
resEle.innerHTML += "<br><br>flat(2): " + JSON.stringify(arr.flat(2));
resEle.innerHTML += "<br>flat(Infinity): " + JSON.stringify(arr.flat(Infinity));
});
</script>
</body>
</html>
Kết quả với các depth khác nhau
Gốc: [1, 2, 3, [4, 5], [6, [7, 8]]]
flat(0): [1, 2, 3, [4, 5], [6, [7, 8]]] (không thay đổi)
flat(1): [1, 2, 3, 4, 5, 6, [7, 8]] (mặc định)
flat(2): [1, 2, 3, 4, 5, 6, 7, 8]
flat(Infinity): [1, 2, 3, 4, 5, 6, 7, 8] (phẳng hoàn toàn)
Ứng dụng thực tế
// 1. Gộp nhiều mảng kết quả từ API
const pages = await Promise.all(urls.map(fetch));
const allItems = pages.flatMap(p => p.data).flat(); // nếu data là mảng lồng
// 2. Xử lý cây thư mục (đệ quy)
function getAllFiles(folder) {
const files = folder.files || [];
const subfolders = folder.folders || [];
return [...files, ...subfolders.flatMap(getAllFiles)];
}
const allFiles = getAllFiles(rootFolder).flat(Infinity);
// 3. Loại bỏ giá trị rỗng (kết hợp filter)
const messy = [1, null, [2, undefined, [3, '', 4]], 5];
const clean = messy.flat(Infinity).filter(Boolean);
// [1, 2, 3, 4, 5]
So sánh flat() vs flatMap()
| Đặc điểm | flat() | flatMap() |
|---|---|---|
| Chức năng chính | Làm phẳng mảng có sẵn | Map + làm phẳng depth 1 |
| Tham số depth | Tùy chỉnh (0, 1, 2... Infinity) | Cố định = 1 |
| Callback | Không có | Bắt buộc |
| Trường hợp dùng | Mảng đã lồng sẵn | Cần biến đổi rồi gộp |
Lưu ý
- Không thay đổi mảng gốc.
- Khoảng trống (empty slots) trong mảng thưa (sparse array) sẽ bị loại bỏ.
- Hỗ trợ: Chrome 69+, Firefox 62+, Safari 12+, Edge 79+.