El siguiente código
function steamrollArray(arr) { // I'm a steamroller, baby return arr.flat(); } steamrollArray([1, [2], [3, [[4]]]]);devoluciones
arr.flatno es una función
Lo probé en Firefox y Chrome v67 y ha ocurrido el mismo resultado.
¿Qué ocurre?
El método flat aún no está implementado en los navegadores comunes (solo Chrome v69, Firefox Nightly y Opera 56). Es una característica experimental. Por lo tanto, no puede usarlo todavía .
Es posible que desee tener su propia función flat en su lugar:
Object.defineProperty(Array.prototype, 'flat', { value: function(depth = 1) { return this.reduce(function (flat, toFlatten) { return flat.concat((Array.isArray(toFlatten) && (depth>1)) ? toFlatten.flat(depth-1) : toFlatten); }, []); } }); console.log( [1, [2], [3, [[4]]]].flat(2) ); El código fue tomado de aquí por Noah Freitas implementado originalmente para aplanar la matriz sin especificar la depth .
Esto también puede funcionar.
let arr = [ [1,2,3], [2,3,4] ]; console.log([].concat(...arr))O para navegadores más antiguos,
[].concat.apply([], arr);Array.flat no es compatible con su navegador. A continuación se presentan dos formas de implementarlo.
Como función, la variable de depth especifica la profundidad a la que se debe aplanar la estructura de la matriz de input (el valor predeterminado es 1; use Infinity para profundizar tanto como sea posible) mientras que la stack es la matriz aplanada, se pasa por referencia en llamadas recursivas y finalmente se devuelve.
function flat(input, depth = 1, stack = []) { for (let item of input) { if (item instanceof Array && depth > 0) { flat(item, depth - 1, stack); } else { stack.push(item); } } return stack; } Como Polyfill, extendiendo Array.prototype si prefiere la sintaxis arr.flat() :
if (!Array.prototype.flat) { Object.defineProperty(Array.prototype, 'flat', { value: function(depth = 1, stack = []) { for (let item of this) { if (item instanceof Array && depth > 0) { item.flat(depth - 1, stack); } else { stack.push(item); } } return stack; } }); }