My understanding is that you want to transform a n×n array such as:
[ ['', '', '', '']
, ['', '', '', '']
, ['', '', '', '']
, ['', '', '', ''] ]
into:
['','','','','','','','','','','','','','','','']
Let's transform the original array into a "matrix of positions" and let's try to picture the "zigzag":
[ [[0,0], [0,1], [0,2], [0,3]]
// ↙ ↗ ↙ ↗
, [[1,0], [1,1], [1,2], [1,3]]
// ↗ ↙ ↗ ↙
, [[2,0], [2,1], [2,2], [2,3]]
// ↙ ↗ ↙ ↗
, [[3,0], [3,1], [3,2], [3,3]]
// ↗ ↙ ↗ ↙
]
If we focus on the edges we can start working out a pattern:
[ [0,0]
, [1,0], /* … */ [0,1]
, [2,0], /* … */ [0,2]
, [3,0], /* … */ [0,3]
, [3,1], /* … */ [1,3]
, [3,2], /* … */ [2,3]
, [3,3] ]
Now we need to work out all the [x,y] between each edges and traverse each edge in opposite direction:
const inp1 = zigzag([ ['', '', '', '']
, ['', '', '', '']
, ['', '☝️', '', '']
, ['', '', '', ''] ]);
const inp2 = zigzag([ ['', '', '']
, ['', '', '']
, ['', '☝️', ''] ]);
const inp3 = zigzag([ ['', '']
, ['', ''] ]);
const inp4 = zigzag([ [''] ]);
console.log(`
[${String(inp1)}]
[${String(inp2)}]
[${String(inp3)}]
[${String(inp4)}]
`);
<script>
const zigzag = inp => {
const m = inp.length - 1;
const edges = [];
for (let x = 0; x <= m; x++) edges.push([x, 0]);
for (let x = 1; x <= m; x++) edges.push([m, x]);
return edges.flatMap(([x, y], i) => {
const path = [[x, y]];
for (let a = x, b = y; a != y && b != x;) path.push([--a, ++b]);
return (i % 2 ? path : path.reverse()).map(([x, y]) => inp[x][y]);
});
}
</script>