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

106
Visualizações
Flatten an array

I want to flatten an array with javascript but without recurssion and without prebuilt function.

This is the code but it dose not flatten the whole array and i want to know what is wrong with my code

input : [1, [2], [3,8, [[4]],9],[5,6]]
output : [1, 2, 3, 8, 5, 6]

Code :

flat = function(array) {
  const output = []
  for (let i = 0; i < array.length; i++) {
    if (typeof array[i] == 'number') {
      output.push(array[i])
    } else {
      let arr = array[i]

      let n = 0
      while (n < arr.length) {
        if (typeof arr[n] == 'number') {
          output.push(arr[n])
          n++
        } else {
          arr = arr[n]
          n--
          console.log(arr, n);
        }
      }
    }
  }
  return output
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's possible to do, but it involves managing a stack yourself, manually:

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

const result = [];
const stack = [{current: input, pos: 0}];
while (stack.length > 0) {
  let {current, pos} = stack.pop();
  if (pos < current.length) {
    let item = current[pos++];
    stack.push({current, pos});
    if (Array.isArray(item)) {
      stack.push({current: item, pos: 0});
    } else {
      result.push(item);
    }
  }
}

console.log(result);

This is what a recursive approach would do in the background, more or less. If your concern about recursion was that you don't like/understand it, not sure that you will find this one more likeable.

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