OneBite.Dev - Coding blog in a bite size

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

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.

← fizz buzz program sample ...
Determine if all string h... →
javascript