chunk
Chunks an array into smaller arrays of a specified size.
1./**2.* Chunks an array into smaller arrays of a specified size.3.**/4.const chunk = <T,>(5.array: T[],6.size: number,7.config?: {8.style: 'normal' | 'repeat' | 'remove';9.},10.): T[][] => {11.const result: T[][] = [];12.13.// Push the chunks into the result array14.for (let i = 0; i < array.length; i += size) {15.result.push(array.slice(i, i + size));16.}17.18.if (config?.style === 'remove' && result[result.length - 1].length !== size) {19.result.pop(); // Remove the last chunk if it doesn't match the size20.} else if (config?.style === 'repeat') {21.// Repeat elements from the start if the last chunk is smaller22.const lastChunk = result[result.length - 1];23.if (lastChunk.length < size) {24.const elementsNeeded = size - lastChunk.length;25.const repeatedElements = array.slice(0, elementsNeeded); // Get elements from the start26.result[result.length - 1] = lastChunk.concat(repeatedElements); // Fill the last chunk27.}28.}29.30.return result;31.};32.33.export default chunk;
1. Installtion
npx @jrtilak/lazykit add chunk
2. Parameters
-
array
(T[]
)
The array to be divided into chunks. The function iterates over this array to create multiple smaller arrays. -
size
(number
)
The desired size for each chunk. Each chunk will contain up to this number of elements, except the last chunk if the array’s length isn't a perfect multiple ofsize
. -
config
(optional) (object
)
An optional configuration object that determines how the function handles the last chunk if it doesn't match the specified size.style
("normal" | "repeat" | "remove"
)
Specifies how to handle the last chunk if it contains fewer elements thansize
:"normal"
: Keeps the last chunk as it is, even if its size is less thansize
."repeat"
: Fills the last chunk with elements from the start of the array until it reaches the specifiedsize
."remove"
: Removes the last chunk if its size is less than the specifiedsize
.
3. Returns
T[][]
Returns an array of arrays, where each inner array (chunk) contains up tosize
elements from the original array. The behavior of the last chunk depends on theconfig.style
option.
4. Type Parameters
T
The type of elements in the array. This allows the function to work with arrays of any type, providing type safety for the elements being chunked.
5. Usage
1. Basic Chunking
1.import chunk from '@/helpers/chunk';2.3.const numbers = [1, 2, 3, 4, 5];4.const result = chunk(numbers, 2);5.// Output: [[1, 2], [3, 4], [5]]6.console.log(result);
This example splits the array into chunks of size 2. The last chunk contains the remaining element.
2. Remove Uneven Length Chunk
1.import chunk from '@/helpers/chunk';2.3.const numbers = [1, 2, 3, 4, 5];4.const result = chunk(numbers, 2, { style: "remove" });5.// Output: [[1, 2], [3, 4]]6.console.log(result);
Here, the last chunk is removed since it contains only one element and does not match the specified size of 2.
3. Repeat Elements to Fill Last Chunk
1.import chunk from '@/helpers/chunk';2.3.const numbers = [1, 2, 3, 4, 5];4.const result = chunk(numbers, 3, { style: "repeat" });5.// Output: [[1, 2, 3], [4, 5, 1]]6.console.log(result);
In this example, the last chunk is filled with elements from the start of the array since it has fewer elements than the specified size of 3.
4. Normal Behavior (Default)
1.import chunk from '@/helpers/chunk';2.3.const numbers = [1, 2, 3, 4, 5];4.const result = chunk(numbers, 3);5.// Output: [[1, 2, 3], [4, 5]]6.console.log(result);
This usage shows the default behavior of the function, where the last chunk is not modified and remains as it is.
5. Using Strings
1.import chunk from '@/helpers/chunk';2.3.const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];4.const result = chunk(fruits, 2, { style: "remove" });5.// Output: [['apple', 'banana'], ['cherry', 'date']]6.console.log(result);
Here, the string array is split into chunks of size 2, and the last chunk is removed because it doesn't meet the size requirement.