Created
October 22, 2015 03:57
-
-
Save petermoresi/400b9a4ec1b3d0ba1d24 to your computer and use it in GitHub Desktop.
Use reduce to chunk flat array into pairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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