Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tincho
Last active March 22, 2020 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tincho/e375b0251fac19be0baf695806c083b4 to your computer and use it in GitHub Desktop.
Save tincho/e375b0251fac19be0baf695806c083b4 to your computer and use it in GitHub Desktop.
// alternative version using ES6 Array.from
const chunkify = (chunkSize, src) => Array.from(
{ length: Math.ceil(src.length/chunkSize) },
(_, i) => src.slice(i * chunkSize, i * chunkSize + chunkSize)
)
/**
* "unflatten" / split array in chunks of given size
*/
function unflatten(src, chunkSize) {
var out = [];
var chunk = [];
for (var i = 0; i < src.length; i++) {
chunk.push(src[i]);
if (chunk.length === chunkSize || (i + 1) === src.length) {
out.push(chunk);
chunk = [];
}
}
return out;
}
var parts = unflatten([1,2,3,4,5,6, 7], 2);
// parts === [ [1, 2], [3, 4], [5, 6], [7] ]
// definition
// flatten(unflatten(someArray, someChunksize)) === someArray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment