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

104
Vistas
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 Respuestas
Responde la pregunta

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 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