--- title: Array.prototype.flat() slug: Web/JavaScript/Reference/Global_Objects/Array/flat tags: - Array - JavaScript - Method - Prototype - Reference - flat translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat ---
flat()
trả về một mảng mới. Trong đó, tất cả các phần tử của mảng con được gán ngược vào nó bằng cách đệ quy lên đến độ sâu đã chỉ định.{{EmbedInteractiveExample("pages/js/array-flat.html")}}
var newArray = arr.flat([depth]);
depth
{{optional_inline}}Một mảng mới với các phần tử của mảng con được nối với nó.
const arr = [1, 2, [3, 4]]; // Trả về mảng chỉ có 1 level arr.flat(); // Nó ngang với việc sử dụng reduce arr.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4] // hoặc decomposition syntax const flattened = arr => [].concat(...arr);
const arr = [1, 2, [3, 4, [5, 6]]]; // ?Sử dụng reduce, concat và deep level function flatDeep(arr, d = 1) { return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), []) : arr.slice(); }; flatDeep(arr, Infinity); // [1, 2, 3, 4, 5, 6]
// Sử dụng stack để đệ quy không cần báo deep level function flatten(input) { const stack = [...input]; const res = []; while(stack.length) { // Lấy gía trị ra khỏi stack const next = stack.pop(); if(Array.isArray(next)) { // Gán trở lại arry, không thay đổi giá trị của item đó stack.push(...next); } else { res.push(next); } } // Đảo ngược array để trả về đúng order ban đầu return res.reverse(); } const arr = [1, 2, [3, 4, [5, 6]]]; flatten(arr); // [1, 2, 3, 4, 5, 6]
function* flatten(array, depth) { if(depth === undefined) { depth = 1; } for(const item of array) { if(Array.isArray(item) && depth > 0) { yield* flatten(item, depth - 1); } else { yield item; } } } const arr = [1, 2, [3, 4, [5, 6]]]; const flattened = [...flatten(arr, Infinity)]; // [1, 2, 3, 4, 5, 6]
Please do not add polyfills on this article. For reference, please check: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500
const arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The flat method removes empty slots in arrays:
const arr5 = [1, 2, , 4, 5]; arr5.flat(); // [1, 2, 4, 5]
Specification |
---|
{{SpecName('ESDraft', '#sec-array.prototype.flat', 'Array.prototype.flat')}} |
{{Compat("javascript.builtins.Array.flat")}}