検索するとreduceを使った実装が出てくるので、forEachで処理したい場合のメモ。
- code
function chunk(list: Array<number>, count: number): Array<Array<number>> {
if (count === 0) {
return [list]
}
let res = new Array<Array<number>>()
let tmp = new Array<number>()
list.forEach((n, index) => {
tmp.push(n)
if ((index + 1) % count === 0) {
res.push(tmp)
tmp = []
}
})
if (tmp.length > 0) {
res.push(tmp)
}
return res
}
console.log(0, chunk( [1,2,3,4,5,6,7,8,9,10], 0))
console.log(1, chunk( [1,2,3,4,5,6,7,8,9,10], 1))
console.log(2, chunk( [1,2,3,4,5,6,7,8,9,10], 2))
console.log(3, chunk( [1,2,3,4,5,6,7,8,9,10], 3))
console.log(4, chunk( [1,2,3,4,5,6,7,8,9,10], 4))
console.log(5, chunk( [1,2,3,4,5,6,7,8,9,10], 5))
console.log(6, chunk( [1,2,3,4,5,6,7,8,9,10], 6))
console.log(7, chunk( [1,2,3,4,5,6,7,8,9,10], 7))
console.log(8, chunk( [1,2,3,4,5,6,7,8,9,10], 8))
console.log(9, chunk( [1,2,3,4,5,6,7,8,9,10], 9))
console.log(10, chunk( [1,2,3,4,5,6,7,8,9,10], 10))
console.log(11, chunk( [1,2,3,4,5,6,7,8,9,10], 11))
- result
[LOG]: 0, [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
[LOG]: 1, [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
[LOG]: 2, [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
[LOG]: 3, [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
[LOG]: 4, [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
[LOG]: 5, [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
[LOG]: 6, [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10]]
[LOG]: 7, [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10]]
[LOG]: 8, [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10]]
[LOG]: 9, [[1, 2, 3, 4, 5, 6, 7, 8, 9], [10]]
[LOG]: 10, [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
[LOG]: 11, [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
- on playgound