I am creating a new matrix where I want to take the rows of the original matrix and make them into columns as well as take the columns of the original matrix and make them into rows.
A matrix of:
[[1,2]
[3,4] [[1,3,5]
[5,6]] turns into [2,4,6]]
When I initialize the new matrix while using the fill() method to create my rows, the insertions duplicate for every row when inserting into a row.
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = new Array(matrix[0].length).fill(new Array()); // initializes array to [ [], [], [] ]
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print
[
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
]
When I initialize my array using a for loop, I do not get duplicate entries
const arrOne = [[1,2,3],[4,5,6],[7,8,9]]
var transpose = function(matrix) {
const transposedArr = [] // initializing using const transposedArr = Array() also works!
for(let i = 0; i < matrix[0].length; i++) { // initializes array to [ [], [], [] ]
transposedArr.push(new Array())
}
//iterate through row
for(let i = 0; i < matrix.length; i++) {
//iterate through columns at row
for(let j = 0; j < matrix[i].length; j++) {
transposedArr[j].push(matrix[i][j])
}
}
return transposedArr;
};
console.log(transpose(arrOne));
This will print:
[
[ 1, 4, 7 ],
[ 2, 5, 8 ],
[ 3, 6, 9 ]
]
ASK: Why is it that when I initialize the array using the fill() method, it is duplicating my insertions for each row?
I came across this issue when working on this Leetcode problem: https://leetcode.com/problems/transpose-matrix/
I also tested this code in repl. It was to make sure it wasn't an issue in Leetcode's environment.