Say I have one large array like
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
and would like to split it into an array of n-tuples like
[[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14] /*, ... */ ] // (for n=2)
Is there some easy way to achieve this? The special case n = 2
would be enough for me.
In python this can be done with
zip(*[iter(xs)]*n)
. Just for fun, here's a JS implementation:Let's start with a poor man's generator (that's all we've got until ES6 spreads around):
zip()
is trivial:Now, to create chained pairs just pass the same iter twice to zip:
For N-pairs an additional utility is required:
Note that like in Python this strips incomplete chunks.
This can be done much simpler by using
Array.slice
:It's also much more efficient: http://jsperf.com/grouper
For an underscore variant, you can achieve this with
_.groupBy()
, grouping by the index of the item:Though, since
_.groupBy()
returns anObject
, getting anArray
takes some additional work:This should work:
Came up with this, it should work for any number of "pockets" or whatever you want to call them. It checks for
undefined
so it works with odd number of items: