2677. Chunk Array

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.

 

Example 1:

Example 2:

Example 3:

Example 4:

Constraints:

  • arr is a valid JSON array
  • 2 < = J S O N . s t r i n g i f y ( a r r ) . l e n g t h < = 1 0 5 2 <= JSON.stringify(arr).length <= 10^5 2<=JSON.stringify(arr).length<=105
  • 1 <= size <= arr.length + 1

From: LeetCode
Link: 2677. Chunk Array


Solution:

Ideas:
This function works by iterating over the array arr in steps of size. In each iteration, it takes a slice of the array of length size starting from the current index, and pushes this slice to the result array. The slice method does not include the end index, so arr.slice(i, i + size) will give an array of length size or less, if the end of the arr array is reached. This ensures that the length of the last subarray may be less than size if arr.length is not evenly divisible by size.
Code:
/**
 * @param {Array} arr
 * @param {number} size
 * @return {Array[]}
 */
var chunk = function(arr, size) {
    var result = [];
    for (var i = 0; i < arr.length; i += size) {
        result.push(arr.slice(i, i + size));
    }
    return result;
};
05-25 13:51