Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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)]),
        []
    )
}
yarnaimo
Webサービスの開発などを行っています。 TypeScript / Firebase / React / Next.js / Node.js / UI Design
https://yarnaimo.vercel.app
admin-guild
「Webサービスの運営に必要なあらゆる知見」を共有できる場として作られた、運営者のためのコミュニティです。
https://admin-guild.slack.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away