Split an Array into Segments

23 September 2020

Updated: 03 September 2023

It can sometimes be useful to split an array into a separated set of rows or columns, such as when trying to separate elements into buckets while maintaing order.

For example, given the following input:

1
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

With the desired output array as follows, in which we split elements into different rows, while maintaing a top-down/left-right ordering:

1
const output = [
2
[1, 4, 7, 10],
3
[2, 5, 8],
4
[3, 6, 9],
5
]

We can accomplish this using a function like so:

1
const transform = (arr, segments) =>
2
[...new Array(segments)].map((_, outerPos) =>
3
input.filter((el, innerPos) => innerPos % segments === outerPos)
4
)

Which can then be used with:

1
const rows = 3
2
const transformedData = transform(input, rows)