I am trying to make a function that coverts all 'horizontal values' of an array into 'vertical values' so that every array[i][j]
turns into newarray[j][i]
[ [ '00', '10', '20' ],
[ '01', '11', '21' ],
[ '02', '12', '22' ] ];
should turn into
[ [ '00', '01', '02' ],
[ '10', '11', '12' ],
[ '20', '21', '22' ] ]
This is they script as I have it currently:
let board =
[ [ '00', '10', '20' ],
[ '01', '11', '21' ],
[ '02', '12', '22' ] ];
let col;
const horizToVert= (arg)=>{
const init = Array(arg.length).fill(Array(arg[0].length).fill(''));
arg.forEach((value, index) => value.forEach((value2, index2) => {
init[index2][index]=value2; console.log(init);
}));
return init;
}
col = horizToVert(board);
However for some reason the output makes no sense to me:
[ [ '00', '', '' ], [ '00', '', '' ], [ '00', '', '' ] ]
[ [ '10', '', '' ], [ '10', '', '' ], [ '10', '', '' ] ]
[ [ '20', '', '' ], [ '20', '', '' ], [ '20', '', '' ] ]
[ [ '20', '01', '' ], [ '20', '01', '' ], [ '20', '01', '' ] ]
[ [ '20', '11', '' ], [ '20', '11', '' ], [ '20', '11', '' ] ]
[ [ '20', '21', '' ], [ '20', '21', '' ], [ '20', '21', '' ] ]
[ [ '20', '21', '02' ],[ '20', '21', '02' ],[ '20', '21', '02' ] ]
[ [ '20', '21', '12' ],[ '20', '21', '12' ],[ '20', '21', '12' ] ]
[ [ '20', '21', '22' ],[ '20', '21', '22' ],[ '20', '21', '22' ] ]
[Finished in 0.727s]
Why is for example '00'
being assigned to all col[i][0]
indices?