How to split array into chunks in JavaScript ?

To split an array into chunks in JavaScript, you can use several methods depending on your needs. Below are detailed explanations and examples for common approaches:

1. Using a for Loop with slice()

Iterate through the array in steps of chunkSize and extract chunks using slice().

function chunkArray(array, chunkSize) {
  const chunks = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    chunks.push(array.slice(i, i + chunkSize));
  }
  return chunks;
}

// Example:
const arr = [1, 2, 3, 4, 5];
console.log(chunkArray(arr, 2)); 
// Output: [[1, 2], [3, 4], [5]]

Explanation:

  • Loop Increment: Move i by chunkSize each iteration.
  • Slice Extraction: Extract from i to i + chunkSize (exclusive).
  • Handles Edge Cases: Automatically stops when i exceeds the array length.

2. Using Array.from()

Leverage Array.from() to create an array of chunks using a mapping function.

function chunkArray(array, chunkSize) {
  return Array.from(
    { length: Math.ceil(array.length / chunkSize) },
    (_, index) => array.slice(
      index * chunkSize,
      (index + 1) * chunkSize
    )
  );
}

// Example:
const arr = ['a', 'b', 'c', 'd'];
console.log(chunkArray(arr, 3)); 
// Output: [['a', 'b', 'c'], ['d']]

Explanation:

  • Array Length: Calculate using Math.ceil(array.length / chunkSize).
  • Map Function: For each index, slice the original array.

3. Using reduce()

Accumulate chunks by grouping elements based on their index.

function chunkArray(array, chunkSize) {
  return array.reduce((result, item, index) => {
    const chunkIndex = Math.floor(index / chunkSize);
    if (!result[chunkIndex]) {
      result[chunkIndex] = []; // Initialize chunk
    }
    result[chunkIndex].push(item);
    return result;
  }, []);
}

// Example:
const arr = [1, 2, 3, 4, 5];
console.log(chunkArray(arr, 2)); 
// Output: [[1, 2], [3, 4], [5]]

Explanation:

  • Chunk Index: Calculate using Math.floor(index / chunkSize).
  • Dynamic Grouping: Build chunks incrementally.

4. Using while Loop

Similar to the for loop but uses a while loop for iteration.

function chunkArray(array, chunkSize) {
  const chunks = [];
  let index = 0;
  while (index < array.length) {
    chunks.push(array.slice(index, index + chunkSize));
    index += chunkSize;
  }
  return chunks;
}

// Example:
const arr = [10, 20, 30, 40, 50];
console.log(chunkArray(arr, 3)); 
// Output: [[10, 20, 30], [40, 50]]

Edge Cases

  • Empty Array: Returns an empty array.
  console.log(chunkArray([], 2)); // Output: []
  • Chunk Size Larger Than Array: Returns a single chunk.
  console.log(chunkArray([1, 2], 5)); // Output: [[1, 2]]
  • Chunk Size of 1: Each element is its own chunk.
  console.log(chunkArray([1, 2, 3], 1)); // Output: [[1], [2], [3]]

Performance Considerations

  • for Loop and slice(): Most efficient for large arrays (minimizes operations).
  • reduce(): Less efficient for huge datasets (processes each element individually).

Summary

MethodUse CaseProsCons
for LoopGeneral-purpose chunking.Efficient, simple.Imperative style.
Array.from()Functional programming approach.Concise, no explicit loop.Slightly less intuitive.
reduce()Incremental grouping.Functional style.Less efficient for large data.
while LoopAlternative loop structure.Clear logic.Similar to for loop.

Choose the method that best fits your coding style and performance requirements. The for loop with slice() is recommended for most cases due to its simplicity and efficiency.

Leave a Reply

Your email address will not be published. Required fields are marked *