let’s say i have an array [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and i want to split it into n parts let’s say 3 part so the result is supposed to be [ 1, 2, 3, 4 ],[ 4, 5, 6, 7],[ 8, 9, 10 ] but the code i have right now is or O(n*m) which is bad. Is there an optimal way of doing this?
const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const n = 3
const result = [[], [], []]
const wordsPerLine = Math.ceil(items.length / 3)
for (let line = 0; line < n; line++) {
for (let i = 0; i < wordsPerLine; i++) {
const value = items[i + line * wordsPerLine]
if (!value) continue //avoid adding "undefined" values
result[line].push(value)
}
}
>Solution :
To split up the array as evenly as possible:
function split_array(a, nparts) {
const quot = Math.floor(a.length / nparts)
const rem = a.length % nparts
var parts = []
for (var i = 0; i < nparts; ++i) {
parts.push(a.splice(0, quot + (i < rem)))
}
return parts
}
var chunks = split_array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)
console.log(JSON.stringify(chunks))
Output:
[[1,2,3,4],[5,6,7],[8,9,10]]
The size of each part will never differ by more than 1.