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

134
Visualizações
How do I recursively call a prototype function inside itself while looping an array in JavaScript?

I'm creating a polyfill of Array.flat() method, however, I'm facing issues while calling the function within itself after checking that the looped element is an array and thats need to be flattened further. When a write a code that is not prototypal, the flattening is proper, however when I try to create a prototype function, I'm unable to get the flattened array. I'm pretty sure that the issue is related with the 'this' keyword. Please have a look at my code.

Here is the code

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

const flatArray = (array) => {
  let output = [];
  const flatten = (array) => {
    for (let i = 0; i < array.length; i++) {
      if (Array.isArray(array[i])) {
        flatten(array[i]);
      } else {
        output.push(array[i]);
      }
    }
    return output;
  };
  return flatten(array);
};

Array.prototype.myFlat = function () {
  let output = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      console.log(this[i]);
      this[i].myFlat();
    } else {
      output.push(this[i]);
    }
  }
  return output;
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In your first piece of code, you create a single output array. When you recursively call flatten, the code is always pushing to the exact same output array, which is in the closure of flatten. Then once everything is done, you return that array.

In the second code, you create a new array every time you recurse. Each recursion will create an array, flatten itself, and then return that new array. But the return value is ignored, so these values don't go anywhere.

You have a few options

  1. Make the code basically identical to your first one, with an internal function for doing the recursion, and a closure variable used by all:
Array.prototype.myFlat = function () {
  let output = [];
  const flatten = (array) => {
    for (let i = 0; i < array.length; i++) {
      if (Array.isArray(array[i])) {
        flatten(array[i]);
      } else {
        output.push(array[i]);
      }
    }
    return output;
  };
  return flatten(this);
}
  1. Pass the output array as a parameter when you recurse:
//                                 VVVVVV--- added parameter
Array.prototype.myFlat = function (output = []) {
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      this[i].myFlat(output); // <---- forward the array along
    } else {
      output.push(this[i]);
    }
  }
  return output;
};
  1. Continue having separate arrays, but then merge them together as the stack unwinds:
Array.prototype.myFlat = function () {
  let output = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      output.push(...this[i].myFlat()); // <---- added output.push
    } else {
      output.push(this[i]);
    }
  }
  return output;
};
about 4 years ago · Juan Pablo Isaza Relatório

0

I am a strong proponent of keeping classes as thin as possible, wrapping functional interfaces wherever possible -

function myFlat(t) {
  return Array.isArray(t)
    ? t.reduce((r, v) => r.concat(myFlat(v)), [])
    : [t]
}

Array.prototype.myFlat = function() { return myFlat(this) }

console.log([1,[2,[3],4],[[5]],6,[[[7]]]].myFlat())
// [ 1, 2, 3, 4, 5, 6, 7 ]

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