こういう感じで、配列を指定数毎に区切りたい
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>>
);
}