티스토리 뷰
내 코드
- 배열 원본 유지하기 위해 slice 메서드 사용
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;
function chunk(arr: Obj[], size: number): Obj[][] {
let result = [];
if (arr.length >= 1) {
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size))
}
}
return result
};
다른 코드 참고한 코드
- 원본 배열을 바꾸는 splice 메서드 사용
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;
function chunk(arr: Obj[], size: number): Obj[][] {
let result = [];
while (arr.length >= 1) {
result.push(arr.splice(0, size))
}
return result
};
댓글