program story

배열을 N 길이의 청크로 분할

inputbox 2020. 9. 20. 09:48
반응형

배열을 N 길이의 청크로 분할 [중복]


이 질문에 이미 답변이 있습니다.

배열 (10 개 항목 포함)을 최대 n항목 을 포함하는 4 개의 청크로 분할하는 방법 .

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
//a function splits it to four arrays.
console.log(b, c, d, e);

그리고 다음과 같이 인쇄됩니다.

['a', 'b', 'c']
['d', 'e', 'f']
['j', 'h', 'i']
['j']

위는 n = 3값이 동적이어야 한다고 가정합니다 .

감사


다음과 같을 수 있습니다.

var arrays = [], size = 3;

while (a.length > 0)
    arrays.push(a.splice(0, size));

console.log(arrays);

splice Array의 방법을 참조하십시오 .


이 코드가 도움이 될 수 있습니다.

var chunk_size = 10;
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
var groups = arr.map( function(e,i){ 
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; 
}).filter(function(e){ return e; });
console.log({arr, groups})

참고 URL : https://stackoverflow.com/questions/11318680/split-array-into-chunks-of-n-length

반응형