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

typescriptでArrayを指定数毎に区切る

Posted at

こういう感じで、配列を指定数毎に区切りたい

describe("chunk test", () => {
  it("number", () => {
    expect(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)).toStrictEqual([
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      [10],
    ]);
  });
  it("string", () => {
    expect(chunk(["one", "two", "three", "four"], 2)).toStrictEqual([
      ["one", "two"],
      ["three", "four"],
    ]);
  });
});

これで出来ました

export function chunk<T>(arr: Array<T>, size: number): Array<Array<T>> {
  return arr.reduce(
    (newarr: Array<Array<T>>, _: T, i: number) =>
      i % size ? newarr : [...newarr, arr.slice(i, i + size)],
    [] as Array<Array<T>>
  );
}
1
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
1
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?