Skip to content

Instantly share code, notes, and snippets.

@tintnaingwin
Created June 23, 2018 06:37
Show Gist options
  • Select an option

  • Save tintnaingwin/ccfb085d361a77fecf2b6c81a9b84edf to your computer and use it in GitHub Desktop.

Select an option

Save tintnaingwin/ccfb085d361a77fecf2b6c81a9b84edf to your computer and use it in GitHub Desktop.
Splitting a JS array into N arrays
function chunkify(a, n, balanced) {
if (n < 2)
return [a];
var len = a.length,
out = [],
i = 0,
size;
if (len % n === 0) {
size = Math.floor(len / n);
while (i < len) {
out.push(a.slice(i, i += size));
}
}
else if (balanced) {
while (i < len) {
size = Math.ceil((len - i) / n--);
out.push(a.slice(i, i += size));
}
}
else {
n--;
size = Math.floor(len / n);
if (len % size === 0)
size--;
while (i < size * n) {
out.push(a.slice(i, i += size));
}
out.push(a.slice(size * n));
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment