--- title: Array.prototype.flat() slug: Web/JavaScript/Reference/Global_Objects/Array/flat translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat original_slug: Web/JavaScript/Referencje/Obiekty/Array/flat ---
Metoda flat() tworzy nową tablicę ze wszystkich elementów, które są podtablicami, łącząc je rekursyjnie z podanym parametrem jak głęboko powinno nastąpić spłaszczenie.
\{{EmbedInteractiveExample("pages/js/array-flatten.html")}}
var newArray = arr.flat([depth]);
depth {{optional_inline}}Nowa tablica składająca się z połączonych elementów podtablic.
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6]
Metoda flat() usuwa puste miejsca w tablicy:
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
reduce i concatvar arr1 = [1, 2, [3, 4]]; arr1.flat(); //to flat single level array arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4] //or const flatSingle = arr => [].concat(...arr);
//to enable deep level flatten use recursion with reduce and concat
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
//non recursive flatten deep using a stack
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
// pop value from stack
const next = stack.pop();
if (Array.isArray(next)) {
// push back array items, won't modify the original input
stack.push(...next);
} else {
res.push(next);
}
}
//reverse to restore input order
return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
//recursive flatten deep
function flatten(array) {
var flattend = [];
!(function flat(array) {
array.forEach(function(el) {
if (Array.isArray(el)) flat(el);
else flattend.push(el);
});
})(array);
return flattend;
}
if (!Array.prototype.flat) {
Array.prototype.flat = function(depth) {
var flattend = [];
(function flat(array, depth) {
for (let el of array) {
if (Array.isArray(el) && depth > 0) {
flat(el, depth - 1);
} else {
flattend.push(el);
}
}
})(this, Math.floor(depth) || 1);
return flattend;
};
}
| Specification | Status | Comment |
|---|---|---|
Array.prototype.flat proposal |
Finished (4) |
{{Compat("javascript.builtins.Array.flat")}}