0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScript: array chunk (配列をn分割)

Last updated at Posted at 2022-04-06

検索すると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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?