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.
This should work:
for (var i=0; i<arr.length; i+=2) {
result.push([arr[i], arr[i+1]]);
}
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:
Array.prototype.pockets = function(n) {
var result = [],
pocket = [],
i, j;
for (i=0; i<this.length; i+=n) {
pocket.length = 0;
for (j=1; j<n; j++) if (this[i+j] != null) pocket.push(this[i+j]);
result.push([this[i]].concat(pocket));
}
if (arguments.length > 1) {
return result.pockets.apply(result, [].slice.call(arguments,1));
}
return result;
};
// Usage:
var arr = [1,2,3,4,5,6,7,8,9,10,11];
arr.pockets(2); //=> [[1,2],[3,4],[5,6],[7,8],[9,10],[11]]
arr.pockets(3); //=> [[1,2,3],[4,5,6],[7,8,9],[10,11]]
// Recursive:
arr.pockets(1,3); //=> [ [[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]], [[10],[11]] ]