chunk
Splits an array into chunks of a specified size. Creates a new array containing subarrays (chunks) of the original array, each with a maximum length of the specified size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size.
Installation
npx fragmen add array/chunkSource Code
/**
* Splits an array into chunks of a specified size.
*
* Creates a new array containing subarrays (chunks) of the original array,
* each with a maximum length of the specified size. The last chunk may contain
* fewer elements if the array length is not evenly divisible by the chunk size.
*
* @tags pure, array-manipulation
* @param {T[]} array The array to split into chunks
* @param {number} size The maximum size of each chunk (must be positive integer)
* @returns {T[][]} A new array containing the chunks, or empty array if input is invalid
*
* @example
* ```typescript
* const numbers = [1, 2, 3, 4, 5, 6, 7];
* const chunks = chunk(numbers, 3);
* console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7]]
*
* const letters = ['a', 'b', 'c', 'd', 'e'];
* const pairs = chunk(letters, 2);
* console.log(pairs); // [['a', 'b'], ['c', 'd'], ['e']]
*
* // Edge cases
* chunk([], 2); // []
* chunk([1, 2, 3], 0); // []
* chunk([1, 2, 3], -1); // []
* ```
*/
export function chunk<T>(array: T[], size: number): T[][] {
// Handle edge cases
if (
!Array.isArray(array) ||
array.length === 0 ||
!Number.isInteger(size) ||
size <= 0
) {
return [];
}
const result: T[][] = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
Examples
const numbers = [1, 2, 3, 4, 5, 6, 7];
const chunks = chunk(numbers, 3);
console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7]]
const letters = ['a', 'b', 'c', 'd', 'e'];
const pairs = chunk(letters, 2);
console.log(pairs); // [['a', 'b'], ['c', 'd'], ['e']]
// Edge cases
chunk([], 2); // []
chunk([1, 2, 3], 0); // []
chunk([1, 2, 3], -1); // []
Related Utilities
compact
arrayRemoves falsy values from an array. Creates a new array with all falsy values removed. Falsy values are: false, null, 0, "", undefined, and NaN. This is useful for cleaning arrays and ensuring only truthy values remain.
difference
arrayCreates an array of values from the first array that are not present in the other arrays. Returns a new array containing elements that exist in the first array but not in any of the subsequent arrays. The order of elements follows the order of the first array. Duplicates in the first array are preserved unless they appear in other arrays.
flatten
arrayFlattens nested arrays to a specified depth. Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. A depth of 1 flattens only the first level of nesting, while Infinity flattens all levels.
group-by
arrayGroups the elements of an array based on the result of a callback function. Creates an object where each key represents a group and the value is an array of items that belong to that group. The grouping is determined by the callback function which is applied to each element.
intersection
arrayFinds the intersection of two or more arrays. Returns a new array containing only the elements that are present in all provided arrays. The order of elements in the result follows the order of the first array. Duplicates are removed from the result.
sort-by
arraySorts an array of objects by a property or using a custom function. Creates a new sorted array without mutating the original. Can sort by a property name (for objects) or by using a custom iteratee function. Supports ascending and descending order.
Quick Actions
Tags
Parameters
arrayT[]The array to split into chunks
sizenumberThe maximum size of each chunk (must be positive integer)
Returns
T[][]A new array containing the chunks, or empty array if input is invalid