Skip to content

Instantly share code, notes, and snippets.

@MaxXxiMast
Created January 21, 2019 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxXxiMast/10215c4e73904d7394b8aaf253b08c22 to your computer and use it in GitHub Desktop.
Save MaxXxiMast/10215c4e73904d7394b8aaf253b08c22 to your computer and use it in GitHub Desktop.
Flatten a 2D Array into a spiral format
//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