when i am using the spread operator to get the element from the variable "matrix" in to the empty array of "result" spread operator is getting all the elements of matrix and putting it in "result" array but when i am performing a looping action on the array it is not giving me the correct output, but when i am not using the spread operator and giving result a normal array, im getting the desired output. Why is this happening?
function rotateImage(n, matrix) {
let result = [...matrix];
let count = 0
for (let i = matrix.length - 1; i >= 0 ; i--) {
for (let j = 0; j < matrix.length; j ) {
result[j][i] = matrix[count][j];
count
j
i
}
count
if(count == 3){
count = 2;
};
}
return result;
}
The above is not working.
But the below is giving the desired output.
function rotateImage(n, matrix) {
let result = [[1,2,3],[4,5,6],[7,8,9]];
let count = 0
for (let i = matrix.length - 1; i >= 0 ; i--) {
for (let j = 0; j < matrix.length; j ) {
result[j][i] = matrix[count][j];
count
j
i
}
count
if(count == 3){
count = 2;
};
}
return result;
}
Why is that?
CodePudding user response:
Make sure that you pass the matrix value in this format: [[1,2,3],[4,5,6],[7,8,9]] then only it'll allow the spread operator to assign in a similar format.
Call the function in this format
rotateImage(n, [[1,2,3],[4,5,6],[7,8,9]])
and it should work.
And for the deep copy, you can do like this
const result = JSON.parse(JSON.stringify(matrix))