Nth item sort JavaScript

A sort function that rearranges an array so every nth item is next to each other.

1
2
3
4
5
6
7
8
9
function mix(items, nth) {
return items.reduce((a, v, i) => {
a[i % nth].push(v);
return i === items.length - 1 ? [].concat(...a) : a;
}, Array(nth).fill().map(a => []))
}
mix([1, 2, 3, 4, 5, 6, 7, 8, 9], 2) // [1, 3, 5, 7, 9, 2, 4, 6, 8]
mix([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) // [1, 4, 7, 2, 5, 8, 3, 6, 9]