
아래 링크의 강의 중 Section 8. Array Chunking의 내용을 추려 이번 글을 작성하였습니다.
The Coding Interview Bootcamp: Algorithms + Data Structures on Udemy
function chunk(array, size) {
const resArr = [];
for (let i = 0; i < array.length; ++i) {
resArr.push(array.slice(size * i, size * (i + 1)));
}
return resArr.filter((el) => el.length >= 1);
}
console.log(chunk([1, 2, 3, 4, 5], 4));
resArr 선언.for문 돌면서 배열 array를 탐색하여 주어진 size만큼 slice() method로 숫자를 잘라서 resArr에 pushfilter() method를 활용하여 resArr 내 빈 배열을 제거하고 결과값을 반환.function chunk(array, size) {
const chunked = [];
for (let element of array) {
const last = chunked[chunked.length - 1];
if (!last || last.length === size) {
chunked.push([element]);
} else {
last.push(element);
}
}
return chunked;
}
console.log(chunk([1, 2, 3, 4, 5], 4));
chunked 선언.for ... of문 돌면서 array의 값을 last에 하나하나 넣어 size만큼 last.length를 증가시킨 다음 last.length가 size와 같거나 last가 존재하지 않으면 나머지 element를 chunked에 push
chunked 반환function chunk(array, size) {
const chunked = [];
let index = 0;
while (index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
}
return chunked;
}
console.log(chunk([1, 2, 3, 4, 5], 4));
chunked 선언.slice() method의 argument로 활용할 변수 index의 초기값을 0으로 설정.index가 array.length보다 작을 동안 while문을 돌면서 빈 배열 chunked에 index를 기준으로 잘라낸 array의 값들을 pushindex는 주어진 size만큼 매회 증가chunked 반환.slice(start, end)
Parameters
start(Optional): 자르기 시작 indexend(Optional): 자르기 끝 index. end의 바로 앞까지를 잘라낸다. 예를 들어 slice(1, 4)로 설정하면 index 1에서 index 3까지의 값을 잘라내어 반환한다.Return value
잘라낸 값들을 담은 새로운 배열을 반환.