728x90

Q. 주어진 array를 주어진 size만큼 잘라서 sub array로 넣어라.

--- Examples
chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/master/completed_exercises/chunk/index.js

😢 undefined 개념, 배열의 마지막 index를 지정하는 방법 그리고 slice를 활용하는 방법을 몰라서 많이 고민했다.

😊 Solution 1)
주어진 array 값을 for ... of를 통해 element로 하나씩 가져오고, 새로운 chunk array가 비어(undefined)있거나 size만큼 꽉차면 새로운 sub array를 push하고, 그게 아니라면 chunk array의 마지막 index sub array에 element를 push하여 해결한다.

Solution 2)
index를 size만큼 쌓아올리는 index 변수를 선언하여, slice(index, index + size); index += size; 를 while loop안에서 반복해준다. 그렇게하면 주어진 길이만큼 slice하여 sub array로 push할 수 있다.

✔ undefined 이용

!undefined는 true

✔ slice(begin, end)

시작부터 끝 전 index까지 array를 잘라준다.
(자세한 내용은 helper method 카테고리에서 확인 가능하다)

Full Code

function chunk(array, size) {
const chunked = [];
let index = 0;
 
while (index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
}
 
return chunked;
}
 
// 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;
// }

+ Recent posts