Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Today
Total
관리 메뉴

고리타분한 개발자

Array Chunking 본문

JavaScript/Algorithm

Array Chunking

sunlee334 2018. 5. 12. 01:16

목적


배열과 나눌 단위가 주어지면, 하나의 배열 안에 단위만큼 내부 배열을 만들기.


example

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]]

1.



![ArrayChunking_1](./erMind/ArrayChunking_1.png)

```js
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
}



2. 


const letters = ['a', 'b', 'c', 'd', 'e']

letters.slice(0, 3) // ['a', 'b', 'c']



function chunk(array, size) {
const chunked = []
let index = 0

while (index < array.length) {
chunked.push(array.slice(index, index + size))
index += size
}

return chunked

]


'JavaScript > Algorithm' 카테고리의 다른 글

Anagrams  (0) 2018.05.12
Fizz Buzz  (0) 2018.05.12
Integer Reversal  (0) 2018.05.12
Paldinromes  (0) 2018.05.12
SentenceCapitalization  (0) 2018.05.12
Comments