문제

Given an array arr and a chunk size size, return a chunked array. A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size.

You may assume the array is the output of JSON.parse. In other words, it is valid JSON.

Please solve it without using lodash's _.chunk function.

https://leetcode.com/problems/chunk-array/

 

예시

 

코드

/**
 * @param {Array} arr
 * @param {number} size
 * @return {Array}
 */
var chunk = function(arr, size) {
    const outputArr = [];
    
    for(let i = 0; i < arr.length; i+=size){
        outputArr.push(arr.slice(i, i+size));
    }
    
    return outputArr;
};

 

 

인자로 들어오는 arr과 size로 새로운 배열을 만들어 리턴해야 한다. arr에 있는 원소들을 size만큼 잘라서 새로운 배열에 넣어주면 된다. Array.prototype.slice()를 이용해서 인자로 들어오는 arr를 size 만큼 잘라주었다.

728x90

+ Recent posts