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

190
Visualizações
Pushing to one element in a nested array is adding to all elements in javascript

I am creating a prefilled nested array and want to push elements to specific indexes, but the elements are being added to all indexes.

let arr = new Array(4).fill([])
arr => Array(4) [ [], [], [], [] ] //this is what I want
arr[0].push(3)
arr => Array(4) [ [3], [3], [3], [3] ] //I only wanted to push 3 to first index,
//why do all indexes have this element?

Any help on how to just update one index would be appreciated.

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

0

let arr = new Array(4).fill([])

This is creating arr as an array of four references to the same array ([] passed as argument). Thus, modifying any of the references modifies the underlying array, and since it's referenced by all of them, you will notice this when logging the object.

> arr[0] === arr[1]
< true

Just use a good ol' for, or even simply [[],[],[],[]] if we are just talking about 4 elements.

let arr = new Array(4)

for (let i = 0; i < arr.length; i++)
    arr[i] = new Array()
> arr[0] === arr[1]
< false
about 4 years ago · Juan Pablo Isaza Relatório

0

This initialization method gives an array of length 4 with an empty array in each element:

[...Array(4)].map(() => []); // [[], [], [], []]

or for example you can use

[...Array(4)].map((_, i) => i); // and get [0, 1, 2, 3]

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