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)
}
}