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): 자르기 시작indexend(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 |
댓글