Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

91
Vistas
Extracting last element of nested array with recursion

I want to flat an array, recursion function calls itself till the last element array but not the last element string, I feel like I am missing something important in understanding how recursion works, the string itself is not added to an empty array.

const nested = [[[[[['string']]]]], 5, '7'];

const funcTest = function (arr) {
  const final = [];
  arr.forEach(el => {
    if (Array.isArray(el)) {
      console.log(el);
      funcTest(el);
    } else final.push(el);
  });
  return final;
};  

console.log(funcTest(nested));

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can Flattening all nested arrays With flat taking argument depth of Infinity:

    const nested = [[[[[["string"]]]]], 5, "7"];
    nested.flat(Infinity); //['string', 5, '7']

depth: The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to add the result of the recursive calls.

const
    nested = [[[[[['string']]]]], 5, '7'];

const funcTest = function (arr) {
  const final = [];
  arr.forEach(el => {
    if (Array.isArray(el)) {
      console.log(el);
      final.push(...funcTest(el)); // <-
    } else final.push(el);
  });
  return final;
};  

console.log(funcTest(nested));

Another recursive approach:

const
    nested = [[[[[['string']]]]], 5, '7'];
    flatValues = item => Array.isArray(item)
        ? item.flatMap(flatValues)
        : item;

console.log(flatValues(nested));

about 4 years ago · Juan Pablo Isaza Denunciar

0

The issue here is that you don't use the return value of the recursive funcTest call.

What you want to do:

const superFlat = (arr) => {
  const result = [];
  
  arr.forEach((item) => {
    if (!Array.isArray(item)) result.push(item);
    else result.push(...superFlat(item));
  });

  return result;
}

Or just use arr.flat(Infinity)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda