Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Flat

15/19
Recursos

Aportes 63

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

La funcionalidad de Flat con recursión

Se busca recursivamente en cada elemento hasta que ya no se encuentre otra lista y se van uniendo los elementos encontrados con Cat.

Dejo también el código por si lo quieren probar:

const matriz = [
    [1,2,3],
    [4,5,6, [1,2, [1,2]]],
    [7,8,9]
];

function profundidad(list) {
    let newList = [];
    if (typeof list != "object") return [list];
    list.forEach(element => {
        newList = newList.concat(profundidad(element));
    });
    return newList;
}

const newArray = profundidad(matriz);

console.log(newArray);


También aporto mi solución, simulando flat con recursividad.
(^_^)

const matriz = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

const flatten = (arr) => arr.reduce((acc, el) => acc.concat(el), []);

console.log(flatten(matriz));

Otra forma de hacer este reto es llamar de forma recursiva a la función en un reduce.

const flatten = arr => arr.reduce(
  (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);
flatten( [1, [2,3], [4,[5,[6]]]] ) // [1, 2, 3, 4, 5, 6]

El método flat() crea una nueva matriz con todos los elementos de sub-array concatenados recursivamente hasta la profundidad especificada.

Lisstoooooooooooooooooo

const matriz = [
    [1, 2, 3],
    [4, 5, 6, [1, 2]],
    [7, 8, 9]
];

// console.log(matriz.flat(2));

function flat(array, deep = 1) {
    const arr = [];

    if (deep < 1) {
        return array;
    }
    array.map(
        (el) => {

            if (Array.isArray(el)) {
                arr.push(...el);
            } else {
                arr.push(el)
            }
        }
    );
    deep -= 1
    return flat(arr, deep);
}


console.log(flat(matriz, 1));

//Expected-> [ 1, 2, 3, 4, 5, 6, [ 1, 2 ], 7, 8, 9 ]

Mi solución aplicando recursividad.

const matriz = [
    0,
    [1,2,3,[4,5]],
    [6,7,[8,9,10,[11,12,13,[14,15]]]]
];
let arrayFinal = [];
console.log("inicial", matriz); // inicial [ 0, [ 1, 2, 3, [ 4, 5 ] ], [ 6, 7, [ 8, 9, 10, [ 11 , 12 , 13 , [ 14 , 15 ] ] ] ] ]

function newArray(array) {
    for (let i = 0; i < array.length; i++) {
        const element = array[i];
        if (element.length > 1) {
            newArray(element);
        } else {
            arrayFinal.push(element);
        }    
    }
    return arrayFinal;
}

console.log("final", newArray(matriz)); // final [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]

Pensándolo un rato, creo que esta forma de aplanar el array es mucho más fácil sin importar el nivel de profundidad:

matrix.join(",").split(",").map((matrixItem) => +matrixItem)
function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(
      Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten
    );
  }, []);
}

console.log(
  flatten([
    [[1, [1.1]], 2, 3],
    [4, 5],
  ])
);

Solucione el reto de tal forma que no se necesite saber cuantos niveles de array se encuentran dentro del array original. Debo aclara que halle a solución sin utilizar el método “flat”, utilice en su lugar una función recursiva en la cual utilice los Arrow Methods “forEach” y “push”. Reconozco que vi unas soluciones en los aportes que me parecen mas efectivas, pero comparto esta que fue la que desarrolle en un principio.

const membrana2 = [
    [1,2,3],
    [4,5,6,[7,8,[10,11,12]]],
    [[13,14,15], [16, [17,18,19],20]]
    
];

let retoArray2 = []; 

function flatArray(matriz) {
    if (Array.isArray(matriz)) {
        matriz.forEach((item) => {
            if (Array.isArray(item)) {
                flatArray(item);
            } else {
                retoArray2.push(item);
            }
        })
    }
}
flatArray(membrana2);
console.log(retoArray2); //Expected output: [1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20]

Esta fue mi solución al problema:

const matriz = [
  [1,2,3],
  [4,5,6, [1,2, [3,4]]],
  [7,8,9]
];

const myFlat = (array) => {
  let newArray = [];
  array.forEach((item) => {
    if (Array.isArray(item)) {
      newArray = newArray.concat(myFlat(item));
    } else {
      newArray.push(item);
    }
  })
  return newArray;
}

console.log("for", myFlat(matriz));

Esto me recordó mucho a la Reducción de dimensionalidad, bastante usado en Machine Learning.

Reto cumplido!! La función aplanarArray declara un arreglo y utiliza la función aplanadora.

En la función aplanadora recibe un item y la referencia de un arreglo, si el item que pasa por parámetro no es un objeto, entonces agregarlo al final del arreglo. De lo contrario, para cada elemento del objeto item, aplicar recursivamente hasta llegar algo distinto de un objeto. Una vez finalizada la función aplanadora, el arreglo newArray de aplanarArray ya estará listo para retornar.
Al ser el pasaje de un objeto por referencia, al trabajar de forma recursiva siempre esteremos pusheando al mismo arreglo.

const matriz = [
    [1,2,3],
    [4,5,6, [1,2, [1,2]]],
    [7,8,9]
];

const matriz2 = [
    1,
    [1,2,3],
    [4,5,6],
    [7,8,[9,10,[11,12]]]
];

function aplanarArray( item ) {
    const newArray = [];
    //Envio el item a aplanar y la referencia al arreglo a retornar
    aplanadora( item, newArray);
    return newArray;
}

function aplanadora( item , arreglo) {
    //Si el item no es un objeto, agregalo al arreglo
    if( typeof item != 'object') {
        arreglo.push(item);
    } else { //De lo contrario
        //Por cada elemento del objeto, aplicar de forma recursiva el metodo hasta llegar a un no-objeto
        item.forEach( element => aplanadora( element, arreglo));
    }
}

const matrizAplanada = aplanarArray( matriz );
const matriz2Aplanada = aplanarArray( matriz2 );
console.log('(Matriz no-aplanada)', matriz);
console.log('(Matriz aplanada)', matrizAplanada);
console.log('(Matriz 2 no-aplanada)', matriz2);
console.log('(Matriz 2 aplanada)', matriz2Aplanada);

Buenos dias compañeros, quisiera recibir feedback de mi codigo, pueden pasarle cualquier arreglo con cualquier nivel.

const algunArray = ['a','b',['c','d','e'],'f',['g','h','i',['j','k',['l','m',['n','o',['p','q']]]]]]

const flat1= (array)=>{
    let newArray =[]
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        newArray.push(...element)       
    }
    return newArray
}
const flatFunction =(array,niveles)=>{
    let arrayFinal = []
    for (let index = 0; index <= niveles-1; index++) {
        if (index === 0){
            arrayFinal = flat1(array) 
            
        }else{
            arrayFinal = flat1(arrayFinal) 
        }               
    }
    console.log(arrayFinal) 
}
// el primer parametro que recibe es el array 
// el segundo parametro es el nivel del arreglo       

flatFunction(algunArray,4)
<code> const matriz = [
    0,[1,2,3,[4,5]],
    [6,7,[8,9,10,[11,12,13,[14,15]]]]
];

function aplanar(array){
  let ret = [];
   for(let i = 0; i < array.length; i++){
       if(Array.isArray(array[i])){
           ret = ret.concat(aplanar(array[i]));
       }else {
           ret.push(array[i]);
       }
       
   }
   return ret;
}

console.log(aplanar(matriz));

Este es mi aporte

pues este no es el codigo mas pequeño , pero quiza sirva como documentacion de como ir llegando a enteder la recursividad
primero empece con tres ciclos for anidados ,
luego reduje a una funcion recursiva pero no me gustaba que tenia q dejar declarado el arrayAplanado fuera de la funcion , asi que al tercer intento (pero luego de horas con pausas icluidas ) tengo esto:

const matriz = [
    [1,2,3],
    [4,5,6 ,[1,2]],
    [7,8,9]
];

function aplanarArray(parametro){
    let arrayPlano = [];
    
    const recursiva=
    (parametro)=>{
        if(Array.isArray(parametro)){
                parametro.forEach(elemento=>recursiva(elemento))
            }else{
                arrayPlano.push(parametro);
            }
            return arrayPlano;
        }
    return recursiva(parametro);
}
console.log("recursiva(matriz) ;" , aplanarArray(matriz));


Mi solución al reto usando reduce y operador terniario

const matriz=[
0,
[1,2,3,[8,78]],
[665,78,[10,95,101,[115,172,143,[14,15]]]]
];

let newArray=[];
function recursiveArray(array){
return array.map(r=>{
r.length > 1
? recursiveArray®
: newArray.push®
}), newArray }

console.log(“New Array”,recursiveArray(matriz));

😊Reto

  • 🪵Con for
const myFlatWithFor = (array, depth) => {
    if (depth === undefined) {
        depth = 1;
    }
    let newArray = [];
    for (let i = 0; i < array.length; i++) {
        const item = array[i];
        if (Array.isArray(item) && depth > 0) {
            newArray = newArray.concat(myFlatWithFor(item, depth - 1));
        } else {
            newArray.push(item);
        }
    }
    return newArray;
}

console.log('myFlatWithFor', myFlatWithFor(matrix));
console.log('myFlatWithFor', myFlatWithFor(matrix, 2));
console.log('myFlatWithFor', myFlatWithFor(matrix, Infinity));
  • 🪚Con for In
const myFlatWithForIn = (array, depth) => {
    if (depth === undefined) {
        depth = 1;
    }
    let newArray = [];
    for (const item in array) {
        if (Array.isArray(array[item]) && depth > 0) {
            newArray = newArray.concat(myFlatWithForIn(array[item], depth - 1));
        } else {
            newArray.push(array[item]);
        }
    }
    return newArray;
}

console.log('myFlatWithForIn', myFlatWithForIn(matrix, 2));

-🪜 Con for of

const myFlatWithForOf = (array, depth) => {
    if (depth === undefined) {
        depth = 1;
    }
    let newArray = [];
    for (const item of array) {
        if (Array.isArray(item) && depth > 0) {
            newArray = newArray.concat(myFlatWithForOf(item, depth - 1));
        } else {
            newArray.push(item);
        }
    }
    return newArray;
}

console.log('myFlatWithForOf', myFlatWithForOf(matrix, 2));

-🪓 Con forEach

const myFlatWithForEach = (array, depth) => {
    if (depth === undefined) {
        depth = 1;
    }
    let newArray = [];
    array.forEach(item => {
        if (Array.isArray(item) && depth > 0) {
            newArray = newArray.concat(myFlatWithForEach(item, depth - 1));
        } else {
            newArray.push(item);
        }
    });
    return newArray;
}
console.log('myFlatWithForEach', myFlatWithForEach(matrix, 3));
  • ⚙️Con reduce
const myFlatWithReduce = (array, depth) => {
    if (depth === undefined) {
        depth = 1;
    }
    return depth > 0 ?
        array.reduce((accumulator, item) => accumulator.concat(Array.isArray(item) ?
            myFlatWithReduce(item, depth - 1) : item), []) :
        array.slice();
};
console.log('myFlatWithReduce', myFlatWithReduce(matrix, Infinity));

-💣 Con Generator

const myFlatWithGenerator = (array, depth) => {
    function* Generator(array, depth) {
        if (depth === undefined) {
            depth = 1;
        }
        for (const item of array) {
            if (Array.isArray(item) && depth > 0) {
                yield* Generator(item, depth - 1);
            } else {
                yield item;
            }
        }
    }
    return [...Generator(array, depth)];
}
console.log('myFlatWithGenerator', myFlatWithGenerator(matrix, 2));

Mi solución recursiva:

const matriz1 = [
	[1, 2, 3],
	[4, 5, 6],
	[7, 8, 9, [11, 25, [32, 15, [1, [2, [3]]]]]],
];
function flatten(data) {
	let newArray = [];
	if (!Array.isArray(data)) {
		return [data];
	} else {
		data.forEach(element => {
			newArray = newArray.concat(flatten(element));
		});
		return newArray;
	}
}
const flatArray = flatten(matriz1);
console.log(flatArray);

Hecho con for y creo que recursividad


const matriz2 = [1, [2, 3], 6, [1],
    [8, 8, 8],
    [1, 2, 3, [4, 4, 5, [1, 0, [10]]]]
];
const newArray = [];

for (let i = 0; i < matriz2.length; i++) {

    if (!matriz2[i].length) {
        newArray.push(matriz2[i])
    } else {
        extraer(matriz2[i]);

    }
}

function extraer(element) {
    const longitud = element.length;
    for (let x = 0; x < longitud; x++) {
        if (!element[x].length) {
            newArray.push(element[x])
        } else {
            extraer(element[x]);
        }
    }
}

console.log(newArray);

Respuesta:

[
  1, 2,  3, 6, 1, 8, 8,
  8, 1,  2, 3, 4, 4, 5,
  1, 0, 10
]

Second challenge solved

Challenge solved

Les comparto mi solución para aplanar un array sin el método flat. 😄

function flatFunction (element) {
    let newArray = [];
    const isElementArray = Object.prototype.toString.call(element) === '[object Array]';
    if (!isElementArray) return element;  
    for (const item of element) {
        newArray = newArray.concat(flatFunction(item));
    }
    return newArray;
}

const matriz = 
[
    [['a', 'b'],1, 2, 3],
    [4, 5, 6, [1, 2, [3, 4]]],
    [7, 8, 9, ['a', 'b']],
];

console.log(flatFunction(matriz));

Mi solucion usarndo recusrividad, usando una funcion:

const names = ['pedro',['juan',[['jose', [[['carlos']]]]]]]

function flatReloaded(array) {
    let newArray= []

    array.forEach(element => {
        if(Array.isArray(element)) {
            newArray = [...newArray, ...flatReloaded(element)]
        } else {
            newArray.push(element)
        }
    })

    return newArray
}

console.log(flatReloaded(names)) //[ 'pedro', 'juan', 'jose', 'carlos' ]

Aprovechando lo aprendido con join y split…

const a = [11,2,3,[4,51],[10,3,[9,14,[11,[15],12]]]];

const ans = a.join(',').split(',').map(item => parseInt(item))
console.log(ans)

Reto: Funcionalidad de flat con recursión

Tomando el curso de complejidad algoritmica aprendí que una función recursiva O(!n) es peor que un bucle anidado O(n^2) así que realize dos algoritmos 1 con recursividad y otro con un bucle for anidado dentro de un While aquí se los dejo:

// using WhileLoop
function Flat(array) {
    let currentArr = array
    let depth = currentArr.length
    let pendingArr = []
    let result = []

    while (depth > 0) {

        for(let i = 0; i < currentArr.length; i++) {
            if( !Array.isArray(currentArr[i]) ) {
                result.push(currentArr[i])
                depth--;
                continue;
            }

            pendingArr.push(currentArr[i])
            depth--;
            depth += currentArr[i].length
        }

        if(pendingArr.length > 0) {
            currentArr = pendingArr.shift()
            depth += pendingArr.length
        }
        
        
    }

    return result

Mi solución con recursividad:

function flatRecursivo (array){
    let newArray = [];
    for(element in array){
        if(!Array.isArray(array[element])){
            newArray.push(array[element]);
        }else{
            newArray = [...newArray, ...flatRecursivo(array[element])];
        }
    }
    return newArray;
}
const matriz = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
];

const newArray = [];
for (let i = 0; i < matriz.length; i++) {
    const array = matriz[i];
    for (let j = 0; j < array.length; j++) {
        const element = array[j];
        newArray.push(element)
    }
}

console.log(newArray);

I didn’t know about flat method, but now I have learned how to use it.

Mi solución.

Se puede seguir mejorando.

Mi solución!

const nums = [1, 2, [3, 4, [5, 6], [7, 8, [9, 10]], 11], 12, { 1: { 2: 3 } }]

const flatArray = (array, newArray = []) => {
    for (const element of array) {
        if (Array.isArray(element)) {
            flatArray(element, newArray)
        } else {
            newArray.push(element)
        }
    }
    return newArray
}

console.log(flatArray(nums))

// expected output
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, { '1': { '2': 3 } } ]

Acá dejo mi solución

const matriz = [
    [1,2,3],
    [4,5,6, [21,22,23, [31,32,33, [41,42,43]]]],
    [7,8,9]
]

function validarElement(arrayIterar) {
    let retorno = [];
    if (Array.isArray(arrayIterar)) {
        for (let index = 0; index < arrayIterar.length; index++) {
            const element = arrayIterar[index];
            if (Array.isArray(element)) {
                retorno = [...retorno,...validarElement(element)];
            } else {
                retorno.push(element);
            }
        }
    } else {
        retorno.push(arrayIterar);
    }
    return retorno;
}

let valor = validarElement(matriz);
console.log(valor);

Con recursiidad

const matriz = [
  [1, 2, 3],
  [4, 5, 6, [1, 2, 3, [1, 4], 3]],
  [7, 8, 9]
];

const newArray = [];
function newFlat(array) {
  for (let i = 0; i < array.length; i++) {
    const e = array[i];
    if (Array.isArray(e)) {
      newFlat(e);
    } else {
      newArray.push(e);
    }
  }
}
newFlat(matriz);
console.log('for', newArray);

Esta es mi solución 🙂

Saludos, les comparto mi solución al desafío. Solo utilicé un ciclo for of y recursividad.

const flatArray = (element, flatElement = []) => {
  for (const i of element) {
    if (!Array.isArray(i)) flatElement.push(i)
    else flatArray(i, flatElement)
  }
  return flatElement
}

const flatMatriz = flatArray(matriz)

Otra forma, aunque es igual que las demás de mis compañeros pero con el operador ternario:D

function flatMethod(matriz) {
  let newArray = [];
  for (element of matriz) {
    Array.isArray(element)
      ? (newArray = newArray.concat(flatMethod(element)))
      : newArray.push(element);
  }
  return newArray;
}

esta es mi solución:

function flat(array) {
    let flatened = [];

    function auxF(aux){
        aux.map((element)=> (Array.isArray(element) ? auxF(element) : flatened.push(element)))
    }

    auxF(array)
    return flatened
}

lo hice de la manera mas compacta que se me ocurrió, para quien le cueste entenderlo solo usé la funcion map con una sintaxis diferente, esto:

aux.map((element)=> (Array.isArray(element) ? auxF(element) : flatened.push(element)))

es lo mismo que esto:

aux.map((element)=>{
            if (Array.isArray(element)) {
                auxF(element)
            }
            else{
                flatened.push(element)
            }
        })    

tambien se puede hacer con un for pero el codigo quedaría muy largo, aquí les dejó todo el codigo:

const matriz = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
]

function flat(array) {
    let flatened = [];

    function auxF(aux){
        aux.map((element)=> (Array.isArray(element) ? auxF(element) : flatened.push(element)))
    }
    auxF(array)
    return flatened
}

const array = flat(matriz)
console.log(array);

Esta fue mi solucion a aplanar el array sin flat, solo con ciclos for:

const matrix = [
    [1,2,3],
    [4,5,6,7,7, [1,2]],
    [7,8,9]
]

matrix.isArray

const newArray = [];

for(let i = 0; i < matrix.length; i++){
    const element = matrix[i];
    for(let ii = 0; ii < matrix[i].length; ii++){
        const finalElement = matrix[i][ii];
        if(!Array.isArray(finalElement)){
            newArray.push(finalElement);
        }else{
            for(let iii = 0; iii < finalElement.length; iii++){
            const finalElement2 = matrix[i][ii][iii];
            newArray.push(finalElement2)
            }
        } 
    }
}

console.log(newArray);

respuesta al reto :

let a = [1,3,2,4,[32,3,[3,5,[1,8],3,3],3,4],2,4]


let newArray = []
function flatByHand(array,resultArray){
  array.forEach(item => {
    if(typeof item == 'object'){
      flatByHand(item,resultArray)
    }else{
      resultArray.push(item)
    }
  })
  return resultArray
}
console.log(flatByHand(a,newArray))

Flat y FlatMap

  • Estos metodos son nuevos en JS

  • Se utilizar para manupular array con array dentro en recursividad

  • Se utiliza para aplanar el array en uno mas simple

function myFlat(arr, deep = 1) {
  let cnt = 0
  let rest= JSON.parse(JSON.stringify(arr))
  while (cnt < deep) {
    rest = rest.reduce((acum, item) => {
      if (item instanceof Array) {
        acum = acum.concat(item)
      }
      else {
        acum.push(item)
      }
      return acum
    }, [])
    cnt++;
  }

  return rest
}

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

console.log(myFlat(arr,2))

Comparto mi solución

Hola! les comparto mi versión del reto 😄:

const hardMatrix = [
  [1, 2, [3, 3]],
  [4, [5, 5, [4, 2]], 6],
  [[1, [2, 3, 4, [3, [2, 1]]]], 8, 9],
];

const recursiveArray = [];

//La función recibe un array y el índice que se quiere evaluar
const flatFunction = (array, index) => {
  // Si el índice ya es igual a lenght no hay comparación por hacer
  if (index === array.length) {
    return;
  }

  // Si el valor del array en ese índice es un objeto, vuelvo a llamar esta función con el índice cero.
  if (typeof array[index] === 'object') {
    flatFunction(array[index], 0);
  } else {
    // Si no es un objeto, es un valor, así que puedo hacer push()
    recursiveArray.push(array[index]);
  }
  // Independiente del If, hay que seguir evaluando las demás posiciones del array recibido.
  flatFunction(array, index + 1);
};

flatFunction(hardMatrix, 0);
console.log('recursive:', recursiveArray);

Aquí esta mi solución al reto:

const array = [1, 2, 3, 4, [5, 6, [7, 8], [9, 10, [11, 12]]], 13, 14, 15, [16, 17, 18, [19, [20]]]];

const newArray = aplanar(array);

console.log(newArray);

function aplanar(array, newArray = undefined) {
    newArray = newArray ? newArray : [];
    array.forEach((item) => {
        if (!Array.isArray(item)) {
            newArray.push(item);
        } else {
            aplanar(item, newArray);
        }
    })
    return newArray;
}

Resultado

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]

Método flat : manipular arrays que tienen arrays dentro y volverlos un solo array.

const matriz = [
  [1, 2, 3],
  [4, 5, 6, [1, 2]],
  [7, 8, 9],
];

const flatMetod = matriz.flat(2);
console.log(flatMetod);

RETO RESUELTO

const matriz = [
  [1, 2, 3],
  [4, 5, 6, [1, 2]],
  [7, 8, 9],
];
const newArray = []
for (let i = 0; i < matriz.length; i++) {
    const matrizElement = matriz[i];
   
    for (let j  = 0; j < matrizElement.length; j++) {
        const element = matrizElement[j];
        //console.log(element.length);
        if(!element.length){ newArray.push( element)}
            else {
                for (let k = 0; k < element.length; k++) {
                    const elementA = element[k];
                    newArray.push( elementA)
            }   
        }
    }  
}

console.log(newArray);
const matriz = [
  [1,2,3],
  [4,5,6,[20,40]],
  [7,8,9]
];

const newArray = []
for (let i = 0; i < matriz.length; i++) {
  const array = matriz[i];
  for (let j = 0; j < array.length; j++) {
    const element = array[j];
    if(Array.isArray(array[j])){
      for (let z = 0; z < element.length; z++) {
        const goku = element[z];
        newArray.push(goku)
      }
    } else {
      newArray.push(element)
    }      
  }
}

console.log('for',newArray)

Esta seria mi manera de encarar un “aplanador” en caso de que halla arrays, dentro de arrays, dentro de un gran array jajaja.

Buen día amigos, mi solución. 💻

<
const matriz = [
    [1,2,[1,5,[1,2]]],
    [4,5,6,[5,6,8],[5,9]],
    [7,8,9,[1,[2,[3]]]]
];

const array = [];

const inspeccion = (object) => {    
    for(const i of object) {
        typeof(i)==='object'? 
            inspeccion(i):
            array.push(i);
    }
}

inspeccion(matriz);
console.log(array);
> 

He intentado hacer el ejercicio aplicando recursividad y me ha salido, aquí os dejo mi código por si a alguien le interesa.

Si les sale el error flat is not defined es posible que solo tengan que actualizar Node, les dejo un link para sus diferentes casos.
How to Update Node.js to Latest Version {Linux, Windows, and macOS}

Mi solución con recursividad 🤗🤗:

Les dejo mi solución con recursividad

const matrix = [
    [1, 2, 3],
    [4, 5, 6, [4, 5, 6]],
    [7, 8, 9, [10, 11, 12, [13, 14, 15]]]
];

const recursiveFlat = (matrix) => {
    let flat = [];
    for (let i = 0; i < matrix.length; i++) {
        if (Array.isArray(matrix[i])) {
            flat = flat.concat(recursiveFlat(matrix[i]));
        } else {
            flat.push(matrix[i]);
        }
    }
    return flat;
}

console.log(recursiveFlat(matrix));
const matriz = [
  [1,2],[3,4,5],6,[6,8,[9,11, [2,3,4,[4,5,2]],13]]
]

const flatArray = (array) =>{

  return (array.reduce((acc,curr) =>(
    Array.isArray(curr) ? 
      acc.concat(flatArray(curr)) :
      acc.concat(curr)
  ),[]))
}

flatArray(matriz)

Comparto mi solución

const matriz = [
    [1,2,3],
  [4,5,6, [1,2, [1,2]]],
  [7,8,9]
];

const newFlat = arr => arr.reduce((acc, cur) => {
    let element = Array.isArray(cur) ? newFlat(cur) : cur;
    return acc.concat(element);
},[])

const rta = newFlat(matriz);
console.log("rta", rta)

Les dejo mi Flat artesanal, implementado con Recursividad y split operator.

const matriz = [
    [1,2,3],
    [4,5,6, [1,2]],
    [7,8,9]
];


function artesanalFlat(array){
    const newArray = [];
    for(let i = 0; i < array.length; i++){
        const element = array[i];
        if(typeof(element) === 'object'){
            newArray.push(...artesanalFlat(element));
        }else{
            newArray.push(element);
        }
       
    }

    return(newArray);
}

const flateredArray = artesanalFlat(matriz);
console.log('El nuevo Array', flateredArray);

Dejo mi aportito de recursion ;D

const arr = [1,2,3, [4,5,6,[3,4],[5,4,[1]]],2,5]

const FLAT = array => {
  let newArray = [];

  if(typeof array == "object") {
    array.forEach(element => {
      newArray = newArray.concat(FLAT(element));
    })
    return newArray
 }

  return array;
}

let flatArray = FLAT(arr);

console.log(flatArray);

Otra solucion

console.clear();

const matriz = [[1, 2, 3], [4, 5, 6, [4, 5, 6]], , [7, 8, 9, [1, 2, 3, [77, 88, 13, [144, 666, 55]]]]];

function flatArray2(array) {
  const newMatriz = [];
  array.forEach((element) => {
    if (Array.isArray(element)) {
      newMatriz.push(...flatArray2(element));
    } else {
      newMatriz.push(element);
    }
  });
  return newMatriz;
}

const newMatriz1 = flatArray2(matriz);
console.log('newMatriz1', newMatriz1);

console.clear();

const matriz = [[1, 2, 3], [4, 5, 6, [4, 5, 6]], , [7, 8, 9, [1, 2, 3, [77, 88, 13]]]];

function getElements(array, newArray) {
  array.forEach((element) => {
    if (Array.isArray(element)) {
      getElements(element, newArray);
    } else {
      newArray.push(element);
    }
  });
}

const newMatriz = [];
getElements(matriz, newMatriz);
console.log('newMatriz', newMatriz);