Created
December 23, 2020 11:59
-
-
Save FrozenIce0617/e8b6d876586ae15e6caba0bfa5b17554 to your computer and use it in GitHub Desktop.
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
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