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:
- Add array b into array a[0]
- Change array b
- 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:
- Read a csv file
- Put line 1 of the csv file into array b.
- Add array b into array a.
- Repeat with line 2 to the end of file.
- 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());