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

230
Visualizações
How do I add an array, change it and add again?

I have this code in order to assemble an array from another array. But I'm not sure why it ONLY copies the last value (Value: 4).

    function test1() {
        var a = [];
        var b = [{"Value": 0}];
        for (let i = 0; i < 5; i++) {
            b[0].Value = i;
            a = a.concat(b);
            console.log(a)
        }
    }

I think I'm doing this:

  1. Add array b into array a[0]
  2. Change array b
  3. Continue with the next slot a[1], a[2], a[3], etc

The problem is the result, at the first loop (i=0) it already returned:

a[0]: {Value: 4}

And at the last loop, all values are 4:

a: {
  a[0]: {Value: 4},
  a[1]: {Value: 4},
  a[2]: {Value: 4},
  a[3]: {Value: 4},
  a[4]: {Value: 4}
}

I wanted the result to be:

a: {
  a[0]: {Value: 0},
  a[1]: {Value: 1},
  a[2]: {Value: 2},
  a[3]: {Value: 3},
  a[4]: {Value: 4}
}

How do I achieve this result?

For what am I doing with this, I am making a website, using javascript to:

  1. Read a csv file
  2. Put line 1 of the csv file into array b.
  3. Add array b into array a.
  4. Repeat with line 2 to the end of file.
  5. Get file a with all lines and make a json file.

I don't know if my explaination is easy enough to understand, and if there's a better way to do this.

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

0

You're updating the same object b and concating it. You can create a new object to concat every time.

   function test1() {
        var a = [];
        for (let i = 0; i < 5; i++) {
            a = a.concat([{"Value": i}]);
            console.log(a)
        }
    }
about 4 years ago · Juan Pablo Isaza Relatório

0

For each iteration b is pointing to the same object reference and it's that reference that is added to the array each time. Move the declaration of b inside the loop so you're creating a new object each time.

function test1() {
  let a = [];
  for (let i = 0; i < 5; i++) {
    const b = [{ value: i }];
    a = a.concat(b);
  }
  return a;
}

console.log(test1());

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