Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda