chunk

Chunks an array into smaller arrays of a specified size.

1. Code

/**
 * Splits an array into chunks of a specified size.
 *
 * @template T - The type of elements in the array.
 * @param {T[]} array - The array to be chunked.
 * @param {number} [size=1] - The size of each chunk.
 * @param {boolean} [strict=false] - Whether to remove the last chunk if it is not equal to the size.
 * @returns {T[][]} - An array of chunks.
 */
const chunk = <T>(
  array: T[],
  size: number = 1,
  strict: boolean = false
  //remove the last chunk if it is not equal to the size
): T[][] => {
  const result: T[][] = [];

  //push the chunks into the result array
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }

  //remove the last chunk if it is not equal to the size
  if (strict && result[result.length - 1].length !== size) {
    result.pop();
  }
  return result;
};

export default chunk;

2. Installation

npx @jrtilak/lazykit@latest add chunk -undefined

3. Description

The chunk function is a utility function in JavaScript that takes an array and divides it into smaller sub-arrays, or "chunks", each with a maximum length equal to a specified size. This function is particularly useful when you need to process a large array in smaller, more manageable pieces.

The function accepts three parameters: the original array to be chunked, the size of each chunk, and a boolean value indicating whether the function should strictly adhere to the chunk size. If the "strict" parameter is set to true, and the last chunk does not meet the specified size, it will be removed from the final result.

4. Props

Prop

Type

Default Value

array*array---
sizenumber1
strictbooleanfalse

5. Examples

import chunk from ".";

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// No size provided, default size is 1
console.log(chunk(arr));
// Expected output: [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]];

// Providing size as 2
console.log(chunk(arr, 2));
// Expected output: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]

// Providing size as 3 and strict as true
console.log(chunk(arr, 3, true));
// Expected output: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]

// Providing size as 4 and strict as true
console.log(chunk(arr, 4, true));
// Expected output: [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]