Chunking array buy n number in javascript
The array chunking problem is another common interview question. The goal is to divide an array into smaller sub-arrays (chunks), where each chunk is of size n
The array chunking problem is another common interview question. The goal is to divide an array into smaller sub-arrays (chunks), where each chunk is of size n. The last chunk may be smaller if there are fewer than n elements left.
Code sample (Solution)
Here’s an efficient way to solve this problem in JavaScript:
function chunkArray(array, n) {
let chunks = [];
for (let i = 0; i < array.length; i += n) {
chunks.push(array.slice(i, i + n));
}
return chunks;
}
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 3;
console.log(chunkArray(array, n));
// Outputs: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Explanation
- We initialize an empty array chunks to hold the chunks.
- Then loop over the input array with a step of n.
- For each iteration, we slice a chunk of size n from the array and push it to chunks.
- The Array.prototype.slice method returns a shallow copy of a portion of the array into a new array object.
Time Complexity Info
The time complexity of this function is O(n), where n is the length of the input array. This is because we’re iterating over the array once, and each operation inside the loop (including slicing and pushing) can be done in constant time. Therefore, this solution is quite efficient.