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
:
1const 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:
1const output = [2 [1, 4, 7, 10],3 [2, 5, 8],4 [3, 6, 9],5]
We can accomplish this using a function like so:
1const transform = (arr, segments) =>2 [...new Array(segments)].map((_, outerPos) =>3 input.filter((el, innerPos) => innerPos % segments === outerPos)4 )
Which can then be used with:
1const rows = 32const transformedData = transform(input, rows)