Skip to content

Instantly share code, notes, and snippets.

@petermoresi
Created October 22, 2015 03:57
Show Gist options
  • Save petermoresi/400b9a4ec1b3d0ba1d24 to your computer and use it in GitHub Desktop.
Save petermoresi/400b9a4ec1b3d0ba1d24 to your computer and use it in GitHub Desktop.
Use reduce to chunk flat array into pairs
[1,1,2,2,3,3,4,4,5].reduce( function(a, b, i) {
if (i === 1) {
return [[a, b]];
} else {
if (i % 2 === 0) {
return a.concat([[b]]);
} else {
return a.splice(0, a.length-1).concat([a[a.length-1].concat(b)]);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment