728x90
반응형
References
아래 링크의 강의 중 Section 8. Array Chunking
의 내용을 추려 이번 글을 작성하였습니다.
The Coding Interview Bootcamp: Algorithms + Data Structures on Udemy
Solution 1. my solution
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
내 빈 배열을 제거하고 결과값을 반환.
Solution 2. with for ... of & if
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
반환
Solution 3. with while & slice()
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()
slice(start, end)
Parameters
start(Optional)
: 자르기 시작index
end(Optional)
: 자르기 끝index
.end
의 바로 앞까지를 잘라낸다. 예를 들어slice(1, 4)
로 설정하면index 1
에서index 3
까지의 값을 잘라내어 반환한다.
Return value
잘라낸 값들을 담은 새로운 배열을 반환.
728x90
반응형
'👩💻 Programming > Coding Test 문제 풀이' 카테고리의 다른 글
첫 글자 대문자로 만들기(Sentence Capitalization) (0) | 2022.04.04 |
---|---|
애너그램(Anagrams) (0) | 2022.04.04 |
fizzBuzz (0) | 2022.04.04 |
문자열 내 최빈값 구하기(MaxChars) (0) | 2022.04.04 |
정수 뒤집기(Integer Reversal) (0) | 2022.04.04 |
댓글