1

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.

Teemu
  • 22,918
  • 7
  • 53
  • 106
BH.Sean
  • 23
  • 3
  • You're accessing the element in the `b` array by reference... Which is why the value it shows is always at the last iteration number... – AdityaParab Sep 28 '21 at 11:12
  • 3
    Because references. `b` remains `b`. It does not become an independent clone of `b` in each loop iteration. You are concatenating to `a` 5 _references_ to `b`, not 5 _independent copies_ of `b`. Whenever you modify `b`, it will affect all of its references, because it's the same one entity in memory. You need to [deep clone](https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript) `b` in each loop iteration. – Jeremy Thille Sep 28 '21 at 11:12

2 Answers2

2

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)
        }
    }
Sandesh Gupta
  • 1,175
  • 2
  • 11
  • 19
2

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());
Andy
  • 61,948
  • 13
  • 68
  • 95