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

Chuyển mảng lồng nhau thành mảng phẳng (flat) với JavaScript

Làm phẳng mảng lồng nhau với Array.flat()

Array.flat([depth]) tạo mảng mới với các phần tử mảng con được ghép nối đệ quy đến độ sâu chỉ định.

Ví dụ từ bài gốc

const arrayObject = [
    [
        { Name: "John" },
        { countryName: "US" }
    ],
    [
        { subjectName: "JavaScript" },
        { teacherName: "Mike" }
    ]
];

// flat() mặc định depth = 1
const output = arrayObject.flat();
console.log(output);
/*
[
  { Name: 'John' },
  { countryName: 'US' },
  { subjectName: 'JavaScript' },
  { teacherName: 'Mike' }
]
*/

Chạy với Node.js

# Lưu file demo.js, chạy:
node demo.js

Các mức depth

const deep = [1, [2, [3, [4, [5]]]]];

deep.flat(0);      // [1, [2, [3, [4, [5]]]]] - không thay đổi
deep.flat(1);      // [1, 2, [3, [4, [5]]]]
deep.flat(2);      // [1, 2, 3, [4, [5]]]
deep.flat(3);      // [1, 2, 3, 4, [5]]
deep.flat(Infinity); // [1, 2, 3, 4, 5] - phẳng hoàn toàn

Ứng dụng thực tế

1. Gộp kết quả từ nhiều API calls

const userPromises = userIds.map(id => fetch(`/api/users/${id}`).then(r => r.json()));
const users = await Promise.all(userPromises);
// users = [[user1], [user2], ...] nếu API trả về array
const flatUsers = users.flat(); // [{...}, {...}, ...]

2. Xử lý cây thư mục / categories

function flattenCategories(categories) {
    return categories.flatMap(cat => [
        cat,
        ...flattenCategories(cat.children || [])
    ]);
}
// Hoặc dùng flat(Infinity) nếu cấu trúc đơn giản
const allCategories = categoriesTree.flat(Infinity);

3. Loại bỏ empty slots (mảng thưa - sparse array)

const sparse = [1, , 3, , 5]; // Empty slots
sparse.flat(); // [1, 3, 5] - tự động loại bỏ empty slots

Polyfill cho trình duyệt cũ

if (!Array.prototype.flat) {
    Array.prototype.flat = function(depth = 1) {
        if (depth === 0) return this.slice();
        return this.reduce((acc, val) => 
            acc.concat(Array.isArray(val) ? val.flat(depth - 1) : val), []);
    };
}

flat() vs flatMap()

const arr = [1, 2, [3, 4]];

// flat: làm phẳng mảng có sẵn
arr.flat(); // [1, 2, 3, 4]

// flatMap: map TRƯỚC, rồi flat depth 1
arr.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6, 4, 8]