logo hsb.horse
← Back to snippets index

Snippets

TypeScript Array Utilities

Collection of type-safe utility functions for common array operations in TypeScript development. Empty array generation, chunking, null filtering, and shuffling.

Published: Updated:

Type-safe utility functions for frequently used array operations in TypeScript development.

emptyArray: Generate Empty Array of Specified Size

Create an array of specific length for initialization, placeholders, or mock data.

function emptyArray(size: number): Array<undefined> {
return Array(size).fill(undefined);
}

chunkArray: Split Array into Chunks

Split an array into chunks of specified size.

function chunkArray<T>(array: T[], size: number): T[][] {
if (size <= 0) return [];
return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>
array.slice(i * size, (i + 1) * size),
);
}

Using Array.from to generate the necessary number of chunks while slicing the original array.

Usage example:

const numbers = [1, 2, 3, 4, 5, 6, 7];
const chunks = chunkArray(numbers, 3);
console.log(chunks);
// Result: [[1, 2, 3], [4, 5, 6], [7]]

filterNonNull: Type-Safe Removal of Null and Undefined

Remove null or undefined from API responses, narrowing TypeScript type from T | null to T.

function filterNonNull<T>(array: Array<(T | null | undefined)>): Array<T> {
return array.filter((v): v is T => v != null);
}

unsafeShuffle: Randomly Shuffle Array

Shuffle array using Fisher-Yates algorithm. Note this is a destructive operation that modifies the original array.

function unsafeShuffle<T>(array: T[]): T[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

Practical Note

This snippet fits well when I do not want to rewrite the same operation or check around typescript, javascript, utilities over and over. Keeping it as a small helper makes the caller easier to read because the intent stays in the foreground.

If the branches and preconditions start growing, it is usually better not to force everything into one snippet. Splitting the steps and helper responsibilities is easier to maintain.