How do you split a large JavaScript array into smaller fixed-size chunks? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you split a large JavaScript array into smaller fixed-size chunks?

message-square
0

To split a large JavaScript array into smaller fixed-size chunks without mutating the original array, loop from 0 to array.length with a step of chunkSize and slice each segment using Array.prototype.slice(i, i + chunkSize) (for (let i = 0; i < array.length; i += chunkSize) { chunks.push(array.slice(i, i + chunkSize)); }). Unlike Array.prototype.splice()—which mutates the source array in place—.slice() creates new chunk arrays cleanly while leaving the input untouched, and validating that chunkSize is a positive integer prevents infinite loops (chunkSize <= 0) or RangeError exceptions.


1. Non-Mutating Chunking with for + Array.prototype.slice()

Step by chunkSize and collect items.slice(i, i + chunkSize) into a new array so the original array stays intact and the final chunk naturally holds any remaining trailing elements:

// Non-mutating helper splitting an array into fixed-size chunks of length <= chunkSize
function chunkArray(items, chunkSize) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
    throw new RangeError("Expected chunkSize to be a positive integer.");
  }

  if (items.length === 0) {
    return [];
  }

  const chunks = [];

  for (let i = 0; i < items.length; i += chunkSize) {
    chunks.push(items.slice(i, i + chunkSize));
  }

  return chunks;
}

// Example usage:
const records = [1, 2, 3, 4, 5, 6, 7];
console.log(chunkArray(records, 3)); // [[1, 2, 3], [4, 5, 6], [7]]
console.log(records);               // [1, 2, 3, 4, 5, 6, 7] (unchanged)
  • Avoids mutation (splice): .slice() copies element references into new chunk arrays without altering items.
  • Handles uneven lengths cleanly: When items.length is not divisible by chunkSize, the last chunk contains the remaining elements ([7] above).

2. Streaming or Lazy Chunk Iteration with a Generator

When processing very large arrays sequentially—such as batching API calls, database inserts, or worker tasks—a generator function yields one chunk at a time without materializing all chunks in memory up front:

// Lazy non-mutating generator yielding fixed-size slices of an array
function* iterateChunks(items, chunkSize) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an array.");
  }

  if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
    throw new RangeError("Expected chunkSize to be a positive integer.");
  }

  for (let i = 0; i < items.length; i += chunkSize) {
    yield items.slice(i, i + chunkSize);
  }
}

// Example usage:
const batchSizes = [];
for (const batch of iterateChunks([10, 20, 30, 40, 50], 2)) {
  batchSizes.push(batch.length);
}
console.log(batchSizes); // [2, 2, 1]
  • Lower peak memory during batch processing: If a batch fails midway or you break early, remaining slices are never allocated.
  • Shallow copy semantics: Each chunk is a new array containing the same object references as items; clone individual items if you plan to mutate nested objects inside a chunk.

3. Recombining Chunks and Edge-Case Handling

If you later flatten chunks back into a single array, chunks.flat() reconstructs the sequence non-mutatingly, and guarding edge cases ([], chunkSize >= items.length, non-integer chunkSize) keeps behavior predictable:

// Non-mutating helper to reassemble chunked arrays back into one array
function flattenChunks(chunks) {
  if (!Array.isArray(chunks)) {
    throw new TypeError("Expected chunks to be an array.");
  }

  return chunks.flat();
}

// Example usage:
const original = ["a", "b", "c", "d"];
const chunks = chunkArray(original, 2);       // [["a", "b"], ["c", "d"]]
const restored = flattenChunks(chunks);       // ["a", "b", "c", "d"]
console.log(chunkArray([], 5));               // []
console.log(chunkArray(["x"], 10));           // [["x"]]
console.log(restored);                        // ["a", "b", "c", "d"]
  • Validate chunkSize strictly: A non-positive (0, -1) or non-integer (1.5, NaN) chunkSize can cause infinite loops or fractional slices if left unvalidated.
  • Prefer slice loop over reduce + slice per element: Stepping