0

when I am using the spread operator to get the element from the variable "matrix" into the empty array of "result" the spread operator is getting all the elements of the matrix and putting them in the "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 the result a normal array, I'm 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?

5
  • What value of matrix you are passing in rotateImage(n, matrix) ? It should be the same as what result look like in your code Commented Dec 20, 2022 at 6:27
  • The spread syntax is making a shallow copy of the array. You need a deep copy. Do you understand the difference? Commented Dec 20, 2022 at 6:27
  • I know why you are passing, but I want to confirm that the value of matrix should be like this : [[1,2,3],[4,5,6],[7,8,9]]. rotateImage(n, [[1,2,3],[4,5,6],[7,8,9]]) Commented Dec 20, 2022 at 6:31
  • no, I dont exactly get it. May i know what the difference between a shallow and a deep copy is? Commented Dec 20, 2022 at 6:31
  • yes you are right ravi agheda Commented Dec 20, 2022 at 6:32

1 Answer 1

1

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)) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.