Skip to content

Instantly share code, notes, and snippets.

@dmitrythaler
Last active August 4, 2022 13:58
Show Gist options
  • Save dmitrythaler/74e91e785f76ab3eacfc1bce9cd32d33 to your computer and use it in GitHub Desktop.
Save dmitrythaler/74e91e785f76ab3eacfc1bce9cd32d33 to your computer and use it in GitHub Desktop.
/** *********************************
* return the contents of the array "arr" divided into "n" equally sized arrays
*
* @param {number[]} arr - input array
* @param {integer} n - number of resulting arrays
*/
const groupArrayElements = (arr, n) => {
if (n === 1) {
return [arr]
}
const len = arr.length
if (len < n) {
// actually this is not necessarily an input error, depends on the requirements, but there are none
throw new Error('WTF!')
}
// const chunk = Math.round(len / n) <-- doesn't work :(
let chunk = Math.floor(len / n)
if (chunk + (len % n) >= n) {
++chunk
}
const res = []
for (let i = 0; i < n - 1; ++i) {
res.push(arr.slice(i * chunk, (i + 1) * chunk))
}
res.push(arr.slice((n - 1) * chunk))
return res
}
// ---------------------------------
// just so see how it works ...
// const getArray = len => Array.from({ length: len }, (_, i) => i + 1)
// console.log( groupArrayElements(getArray(6), 1) )
// console.log( groupArrayElements(getArray(6), 3) )
// console.log( groupArrayElements(getArray(6), 5) )
// console.log( groupArrayElements(getArray(6), 6) )
// console.log( groupArrayElements(getArray(3), 2) )
// console.log( groupArrayElements(getArray(11), 5) )
// console.log( groupArrayElements(getArray(12), 5) )
// console.log( groupArrayElements(getArray(13), 5) )
// console.log( groupArrayElements(getArray(14), 5) )
// console.log( groupArrayElements(getArray(15), 5) )
// console.log( groupArrayElements(getArray(16), 5) )
// with results like ...
// [[1, 2, 3, 4, 5, 6]]
// [[1, 2], [3, 4], [5, 6]]
// [[1], [2], [3], [4], [5, 6]]
// [[1], [2], [3], [4], [5], [6]]
// [[1, 2], [3]]
// [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10, 11]]
// [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10, 11, 12]]
// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13]]
// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14]]
// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15] ]
// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15, 16]]
// here be tests ...
// for (let l = 3; l < 1000; ++l) {
// for (let n = 2; n < l; ++n) {
// // console.log(`l ${l}, n ${n}`)
// const grouped = groupArrayElements(getArray(l), n)
// assert.equal(grouped.length, n)
// const lastItem = grouped[grouped.length - 1]
// const prevLastItem = grouped[grouped.length - 2]
// assert.ok(
// grouped.length === 1 ||
// lastItem.length <= prevLastItem.length ||
// lastItem.length < n
// )
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment