Created
January 21, 2019 16:33
-
-
Save MaxXxiMast/10215c4e73904d7394b8aaf253b08c22 to your computer and use it in GitHub Desktop.
Flatten a 2D Array into a spiral format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//ES6 | |
function spiral(matrix) { | |
const arr = []; | |
while (matrix.length) { | |
arr.push( | |
...matrix.shift(), | |
...matrix.map(a => a.pop()), | |
...(matrix.pop() || []).reverse(), | |
...matrix.map(a => a.shift()).reverse() | |
); | |
} | |
return arr; | |
} | |
const array2d = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]; | |
const spiral_array = spiral(array2d); | |
spiral_array(); | |
// Output: [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment