🔗LC2677 🟢 Easy 🧩 Pattern – JSON and Arrays
📅 Day 21/30 Days of JavaScript
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 the size of 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
Input: arr = [1,2,3,4,5], size = 1
Output: [[1],[2],[3],[4],[5]]
Explanation: The arr has been split into subarrays each with 1 element.
Input: arr = [1,9,6,3,2], size = 3
Output: [[1,9,6],[3,2]]
Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.
Code language: JavaScript (javascript)Solution
/**
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
var chunk = function (arr, size) {
const result = [];
let temp = [];
for (let i = 0; i < arr.length; i++) {
temp.push(arr[i]);
if (temp.length === size || i === arr.length - 1) {
// Push subarray when we reach chunk size or end of array
result.push(temp);
temp = [];
}
}
return result;
};Code language: JavaScript (javascript)