In Typescript:
I have a 1D array of objects: my1dArray
.
I am copying 5 x each row of my1dArray
into a 2D array my2dArray
(so I end up with a my2dArray[3][5]
).
I then reset the id element for each row of the my2dArray
.
For my2dArray[0]
, I end up with this (id=4):
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
What I thought I would get is this:
{id: 0, surname: "Smith", givenNames: "Linda"}
{id: 1, surname: "Smith", givenNames: "Linda"}
{id: 2, surname: "Smith", givenNames: "Linda"}
{id: 3, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
The rest of the my2dArray[4][5]
array has the same problem.
What am I doing wrong?
//Create 1d Array
let my1dArray: any[];
my1dArray = [
{ id: 0, surname: 'Smith', givenNames: 'Linda'},
{ id: 0, surname: 'Bloggs', givenNames: 'Bill'},
{ id: 0, surname: 'Jones', givenNames: 'Jim'},
];
//Initalise 2d Array
let my2dArray = init2DArray(3, 5, function () {
return 0
});
let j = 0;
let k = 0;
for (let i = 0; i < my1dArray.length; i++) {
for (let count = 0; count < 5; count++) {
my2dArray[j][count] = my1dArray[i];
//reset the id
my2dArray[j][count].id = k;
k++;
}
j++;
}
console.log('myNewData', my2dArray[0]);
/////Intialisation function///////////////
function init2DArray(xlen, ylen, factoryFn) {
let ret = [];
for (let x = 0; x < xlen; x++) {
ret[x] = [];
for (let y = 0; y < ylen; y++) {
ret[x][y] = factoryFn(x, y)
}
}
return ret
}