Array Chunking
JavaScript
easy
10 mins
Write a function that splits an array into chunks (subarrays) of a given size n. If the array cannot be split evenly, the final chunk should contain the remaining elements.
Input:
- An array of elements
arr - A positive integer
nrepresenting the size of each chunk
Output:
- An array of subarrays, each with a length of
n(except possibly the last one)
Example Inputs & Outputs
// Example 1: Input: ([1, 2, 3, 4], 2) Output: [[1, 2], [3, 4]] // Example 2: Input: ([1, 2, 3, 4, 5], 2) Output: [[1, 2], [3, 4], [5]] // Example 3: Input: ([], 3) Output: [] // Example 4: Input: ([1, 2, 3], 5) Output: [[1, 2, 3]]
Constraints & Edge Cases
- The chunk size
nis a positive integer greater than 0. - The input array can be empty.
- If
nis larger than the array length, return a single chunk with the entire array. - If
nis 1, return an array of single-element arrays.
Companies:
stripe
paypal
zomato
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
