Esta página ha sido traducida del inglés por la comunidad.Aprende más y únete a la comunidad de MDN Web Docs.
Array.prototype.flat()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since enero de 2020.
Experimental:Esta es unatecnología experimental
Comprueba laTabla de compabilidad de navegadores cuidadosamente antes de usarla en producción.
El métodoflat() crea una nueva matriz con todos los elementos de sub-array concatenados recursivamente hasta la profundidad especificada.
In this article
Pruébalo
const arr1 = [0, 1, 2, [3, 4]];console.log(arr1.flat());// expected output: Array [0, 1, 2, 3, 4]const arr2 = [0, 1, [2, [3, [4, 5]]]];console.log(arr2.flat());// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]console.log(arr2.flat(2));// expected output: Array [0, 1, 2, 3, Array [4, 5]]console.log(arr2.flat(Infinity));// expected output: Array [0, 1, 2, 3, 4, 5]Sintaxis
var newArray = arr.flat([depth]);
Parámetros
depthOpcionalEl nivel de profundidad que especifica qué tan profunda debe aplanarse una estructura de matriz anidada. El valor predeterminado es 1.
Valor de retorno
Una nueva matriz con los elementos de la sub-matriz concatenados en ella.
Ejemplos
>Aplanar matrices anidadas
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]Aplanamiento y huecos de matriz
El método de aplanar elimina las ranuras vacías en las matrices:
var arr4 = [1, 2, , 4, 5];arr4.flat();// [1, 2, 4, 5]Alternativa
>reduce yconcat
var arr1 = [1, 2, [3, 4]];arr1.flat();//aplanar una matriz de nivel únicoarr1.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4]//oconst flatSingle = (arr) => [].concat(...arr);//para permitir el aplanamiento a nivel profundo use recursión con reduce y concatvar 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]//aplanamiento profundo no recursivo usando un stackvar arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]];function flatten(input) { const stack = [...input]; const res = []; while (stack.length) { // elimina ultimo valor del stack const next = stack.pop(); if (Array.isArray(next)) { // agrega de nuevo los items al array, sin modificar la entrada original stack.push(...next); } else { res.push(next); } } //invierte para restaurar el orden de entrada return res.reverse();}flatten(arr1); // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]//Aplanamiento profundo recursivofunction flatten(array) { var flattend = []; !(function flat(array) { array.forEach(function (el) { if (Array.isArray(el)) flat(el); else flattend.push(el); }); })(array); return flattend;}Polyfill
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; };}Especificaciones
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-array.prototype.flat> |