chunk
arrays
Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.
Installation
Import
import { chunk } from '@tulx/utils';Source Code
Implementation
/**
* Creates an array of elements split into groups the length of size.
* If array can't be split evenly, the final chunk will be the remaining elements.
*
* @param array - The array to process.
* @param size - The length of each chunk.
* @returns The new array of chunks.
*
* @example
* ```ts
* chunk(['a', 'b', 'c', 'd'], 2); // [['a', 'b'], ['c', 'd']]
* chunk(['a', 'b', 'c', 'd'], 3); // [['a', 'b', 'c'], ['d']]
* ```
*/
export function chunk<T>(array: readonly T[], size: number): T[][] {
if (size <= 0) {
return [];
}
const result: T[][] = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
Example
import { chunk } from '@tulx/utils';
chunk(['a', 'b', 'c', 'd'], 2); // [['a', 'b'], ['c', 'd']]
chunk(['a', 'b', 'c', 'd'], 3); // [['a', 'b', 'c'], ['d']]Related Functions
compact
Creates an array with all falsy values removed. The values false, null, 0, "", undefined, and NaN are falsy.
concat
Creates a new array concatenating array with any additional arrays and/or values.
difference
Creates an array of array values not included in the other given arrays. The order and references of result values are determined by the first array.
differenceBy
This method is like difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared.
differenceWith
This method is like difference except that it accepts comparator which is invoked to compare elements of array to values.
drop
Creates a slice of array with n elements dropped from the beginning.