Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Organization

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

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)]),
        []
    )
}
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
10
Help us understand the problem. What are the problem?