Skip to content

Instantly share code, notes, and snippets.

@FrozenIce0617
Created December 23, 2020 11:59
Show Gist options
  • Save FrozenIce0617/e8b6d876586ae15e6caba0bfa5b17554 to your computer and use it in GitHub Desktop.
Save FrozenIce0617/e8b6d876586ae15e6caba0bfa5b17554 to your computer and use it in GitHub Desktop.
const groupArrayElements = (arr, N) => {
const res = [];
const rem = arr.length % N;
const cnt = parseInt(arr.length / N);
let temp = [];
let groupCnt = 0;
let groupPos = 0;
arr.forEach((element) => {
if (groupCnt < cnt || (groupCnt < cnt + 1 && groupPos < rem)) {
} else {
groupPos += 1;
groupCnt = 0;
res.push(temp);
temp = [];
}
temp.push(element);
groupCnt += 1;
});
res.push(temp);
for (let i = 0; i < N - res.length; i++) {
res.push([]);
}
return res;
};
console.log(groupArrayElements([1, 2, 3, 4, 5], 3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment