리터럴과 숫자의 배열을 받아서 배열(첫 번째 인수)을 길이가 n인 그룹으로 나누고(두 번째 인수) 이렇게 형성된 2차원 배열을 반환하는 JavaScript 함수를 작성해야 합니다.
배열과 숫자가 -
인 경우const arr = ['a', 'b', 'c', 'd']; const n = 2;
그러면 출력은 다음과 같아야 합니다. -
const output = [['a', 'b'], ['c', 'd']];
예시
이제 코드를 작성해 보겠습니다 -
const arr = ['a', 'b', 'c', 'd'];
const n = 2;
const chunk = (arr, size) => {
const res = [];
for(let i = 0; i < arr.length; i++) {
if(i % size === 0){
// Push a new array containing the current value to the res array
res.push([arr[i]]);
}
else{
// Push the current value to the current array
res[res.length-1].push(arr[i]);
};
};
return res;
};
console.log(chunk(arr, n)); 출력
콘솔의 출력은 -
[ [ 'a', 'b' ], [ 'c', 'd' ] ]