23
14

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 5 years have passed since last update.

✂️ TypeScript/JavaScript - 配列を一定の個数ごとに分割する

Last updated at Posted at 2019-03-02

Ruby の each_slice、PHP の array_chunk みたいなやつです。
例えば [1, 2, 3, 4, 5, 6, 7] を3個ずつに分けて [[1, 2, 3], [4, 5, 6], [7]] を作りたい場合などに使えると思います。

TypeScript

function chunk<T extends any[]>(arr: T, size: number) {
    return arr.reduce(
        (newarr, _, i) => (i % size ? newarr : [...newarr, arr.slice(i, i + size)]),
        [] as T[][]
    )
}

chunk([1, 2, 3, 4, 5, 6, 7], 3) // -> [[1, 2, 3], [4, 5, 6], [7]]

JavaScript

function chunk(arr, size) {
    return arr.reduce(
        (newarr, _, i) => (i % size ? newarr : [...newarr, arr.slice(i, i + size)]),
        []
    )
}
23
14
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
23
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?