I'm trying to practice solving JS coding problems. Given an array matrix, unroll the array in clockwise rotation.
// Sample Array
// 1 2 3 4
// 12 13 14 5
// 11 16 15 6
// 10 9 8 7
matrix = [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
// expected output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
matrix2 = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
// expected output
["a", "b", "c", "f", "i", "h", "g", "d", "e"]
I wrote the following solution, but it keeps crashing when it tries to revere the bottom array. I keep getting Uncaught TypeError: Cannot read property 'reverse' of undefined.
What is odd about this is that I found multiple solutions online to this coding challenge, and they're all similar to this solution. I tried copying/pasting these solutions, but when I run them, I still get the same error above. (example 1, example 2).
How can I improve my code to avoid this error and achieve the desired results?
function unrollMatrix(array) {
let newArray = [];
while (array.length > 0) {
// Get top row
results = [...newArray, array.shift()];
// Get right column
results = [...newArray, array.map(row => row.pop())];
// Get bottom row in reverse
results = [...newArray, array.pop().reverse()];
// Get left column in reverse
results = [...newArray, array.map(row => row.shift()).reverse()];
}
return newArray.flat();
}