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

177
Visualizações
Why am I getting an array with six Array(6) instead of six Array(1)?

I was trying to get an array with some arrays inside of it, and each of those inner arrays should contain ONE of the n powers of 2, not all.

let n = 5;
    let arr = Array(n + 1).fill([]);
    const transform = function (el, i) {
      el.push(2 ** i);
    };
    console.log(arr); // [Array(0), Array(0), Array(0), Array(0), Array(0), Array(0)]
    arr.map(transform);
    
    console.log(arr); //[Array(6), Array(6), Array(6), Array(6), Array(6), Array(6)]
    //was expecting //[[1], [2], [4], [8], [16], [32]]

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

When using fill, they share the same instance. So changing one changes all the others. You need to use map after filling

new Array(6).fill(null).map(() => []).map(transform)
about 4 years ago · Juan Pablo Isaza Relatório

0

It may be easier to use a traditional for loop to accomplish your end result. Using map and transform is a more roundabout way of doing the following:

let n = 5;
let arr = [];
for (let i = 0; i <= n; i++) {
  arr.push([2**i]);
}
console.log(arr);

about 4 years ago · Juan Pablo Isaza Relatório

0

Fill is just setting every index with a reference to that array. It is not creating a new array in every index.

The easiest way to create an array and fill it with empty arrays is with Array.from

const n = 5;
const transform = (arr, index) => arr.push(2 ** index);
const myArray = Array.from({length: n}, () => []);
myArray.forEach(transform);
console.log(myArray);

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