Leetcode: Rotate Image

Challenge: 
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).

Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Expected Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Here’s our starter code below:

var rotate = function(matrix) {

};

What we do know: 
1. We have to loop through the array
2. Within each array, we need an inner loop to capture each value
3. When we capture one value, we’ll immediately place that value in its appropriate index — for this we’ll have a tracker variable that keeps track of our matrix length, and decrement as we place each value
4. When both loops are finished, return the matrix (leetcode doesn’t require this, but it’s always great to see the finished product!)

Whiteboard to find the pattern to this solution:

From the (beautiful) diagram above, you can see an apparent pattern where we pop the values from the first array set then unshift that value to the last array set.

var rotate = function(matrix) {
// iterate through array
for (var i = 0; i <= matrix.length-1; i++) {
  // keeps track of our matrix length inside of inner loop
var tracker = matrix.length-1;

// inner loop that starts at the end of the matrix length
for (var j = matrix.length-1; j >= 0; j--) {
      // assigns the popped value to current
var current = matrix[i].pop();
      // unshifts the valued assigned to current to the first position of last array
matrix[tracker].unshift(current);
      // decrement tracker after each j iteration
tracker--;
}
}
return matrix;
};

It’s difficult to add comments without some colors in the code block, so here’s a visual of our iterations:

i — j —tracker — matrix — — — — — — — — — — popped value
i: 0 j: 2 tacker: 2 [ [ 1, 2 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] current: 3
i: 0 j: 1 tacker: 1 [ [ 1 ], [ 4, 5, 6 ], [ 3, 7, 8, 9 ] ] current: 2
i: 0 j: 0 tacker: 0 [ [], [ 2, 4, 5, 6 ], [ 3, 7, 8, 9 ] ] current: 1
i: 1 j: 2 tacker: 2 [ [ 1 ], [ 2, 4, 5 ], [ 3, 7, 8, 9 ] ] current: 6
i: 1 j: 1 tacker: 1 [ [ 1 ], [ 2, 4 ], [ 6, 3, 7, 8, 9 ] ] current: 5
i: 1 j: 0 tacker: 0 [ [ 1 ], [ 5, 2 ], [ 6, 3, 7, 8, 9 ] ] current: 4
i: 2 j: 2 tacker: 2 [ [ 4, 1 ], [ 5, 2 ], [ 6, 3, 7, 8 ] ] current: 9
i: 2 j: 1 tacker: 1 [ [ 4, 1 ], [ 5, 2 ], [ 9, 6, 3, 7 ] ] current: 8
i: 2 j: 0 tacker: 0 [ [ 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ] current: 7
FINAL: [ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]