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

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

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 Denunciar

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