← Back to challenges

Spiral Transposition

JavaScriptHardarraysloopsmathrecursion

Instructions

Create a function that takes a two-dimensional array as an argument and returns a one-dimensional array with the values of the original 2d array that are arranged by spiralling through it (starting from the top-left).

Examples

spiral([
  [7, 2],
  [5, 0]
])

➞ [7, 2, 0, 5]

spiral([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
])

➞ [1, 2, 3, 6, 9, 8, 7, 4, 5]

spiral([
  [1, 1, 1],
  [4, 5, 2],
  [3, 3, 2]
])

➞ [1, 1, 1, 2, 2, 3, 3, 4, 5]

Notes

If you do not understand the instructions, write the 3x3 array example on a piece of paper and trace the output through it.

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.