Home > other >  How do I add an array, change it and add again?
How do I add an array, change it and add again?

Time:09-28

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.

CodePudding user response:

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

CodePudding user response:

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());

  • Related