Skip to content

Instantly share code, notes, and snippets.

@jovey-zheng
Created July 28, 2016 01:07
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 jovey-zheng/687c8d0091c1e3c3917fa5875c37fd8b to your computer and use it in GitHub Desktop.
Save jovey-zheng/687c8d0091c1e3c3917fa5875c37fd8b to your computer and use it in GitHub Desktop.
Transform an array to some chunk array.
function chunk(arr, chunk) {
var res = [],
len = arr.length,
_len = Math.ceil(arr.length / chunk),
_chunk = 0;
chunk = chunk > len ? len : chunk;
for (var i = 0; i < _len ;i++) {
var _arr = [];
if (i === _len - 1 && chunk > _len) {
for (var j = 0; j < (len - chunk); j++) {
_arr.push(arr[_chunk + j]);
}
} else {
for (var j = 0; j < chunk; j++) {
_arr.push(arr[_chunk + j]);
}
}
_chunk = chunk + _chunk;
res.push(_arr);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment