Comprehensive array manipulation utilities providing type-safe operations for converting, filtering, transforming, and organizing arrays.
Convert between different array-like structures with type safety.
/**
* Convert `Arrayable<T>` to `Array<T>`
* @param array - Value or array to convert
* @returns Array containing the input value(s)
*/
function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
/**
* Convert `Arrayable<T>` to `Array<T>` and flatten it
* @param array - Value or array to flatten
* @returns Flattened array
*/
function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
/**
* Use rest arguments to merge arrays
* @param args - Arrays to merge
* @returns Merged array
*/
function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;Usage Examples:
import { toArray, flattenArrayable, mergeArrayable } from "@antfu/utils";
// Convert single values or arrays
const single = toArray("hello"); // ["hello"]
const existing = toArray(["a", "b"]); // ["a", "b"]
const nullable = toArray(null); // []
// Flatten nested arrays
const flattened = flattenArrayable([1, [2, 3], 4]); // [1, 2, 3, 4]
// Merge multiple array-like inputs
const merged = mergeArrayable("a", ["b", "c"], null, ["d"]); // ["a", "b", "c", "d"]Divide arrays into multiple groups based on filter functions.
type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
/**
* Divide an array into two parts by a filter function
*/
function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];Usage Examples:
import { partition } from "@antfu/utils";
// Simple two-way partition
const [odds, evens] = partition([1, 2, 3, 4, 5], i => i % 2 !== 0);
// odds: [1, 3, 5], evens: [2, 4]
// Multi-way partition
const [small, medium, large] = partition(
[1, 5, 10, 15, 25, 30],
n => n < 10, // small numbers
n => n < 20 // medium numbers (large numbers go to the third array)
);
// small: [1, 5], medium: [10, 15], large: [25, 30]Remove duplicate elements from arrays with various comparison strategies.
/**
* Unique an Array using Set comparison
* @param array - Array to make unique
* @returns Array with unique elements
*/
function uniq<T>(array: readonly T[]): T[];
/**
* Unique an Array by a custom equality function
* @param array - Array to make unique
* @param equalFn - Custom equality comparison function
* @returns Array with unique elements based on custom comparison
*/
function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];Usage Examples:
import { uniq, uniqueBy } from "@antfu/utils";
// Simple uniqueness
const unique = uniq([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4]
// Custom uniqueness by property
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 1, name: "Alice" }, // duplicate
];
const uniqueUsers = uniqueBy(users, (a, b) => a.id === b.id);
// [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }]Access and modify array elements with safe indexing and manipulation functions.
/**
* Get last item from array
*/
function last(array: readonly []): undefined;
function last<T>(array: readonly T[]): T;
/**
* Get nth item of Array. Negative for backward indexing
* @param array - Array to access
* @param index - Index (supports negative indexing)
* @returns Element at the specified index
*/
function at(array: readonly [], index: number): undefined;
function at<T>(array: readonly T[], index: number): T;
/**
* Remove an item from Array
* @param array - Array to modify (mutated)
* @param value - Value to remove
* @returns True if item was found and removed
*/
function remove<T>(array: T[], value: T): boolean;
/**
* Move element in an Array
* @param arr - Array to modify (mutated)
* @param from - Source index
* @param to - Destination index
* @returns The modified array
*/
function move<T>(arr: T[], from: number, to: number): T[];Usage Examples:
import { last, at, remove, move } from "@antfu/utils";
const items = ["a", "b", "c", "d"];
// Access elements
const lastItem = last(items); // "d"
const secondLast = at(items, -2); // "c"
const first = at(items, 0); // "a"
// Modify arrays
const success = remove(items, "b"); // true, items is now ["a", "c", "d"]
move(items, 0, 2); // items is now ["c", "d", "a"]Generate arrays with specific patterns and ranges.
/**
* Generate a range array of numbers. The `stop` is exclusive.
*/
function range(stop: number): number[];
function range(start: number, stop: number, step?: number): number[];
/**
* Clamp a number to the index range of an array
* @param n - Number to clamp
* @param arr - Array to use for range bounds
* @returns Clamped index value
*/
function clampArrayRange(n: number, arr: readonly unknown[]): number;Usage Examples:
import { range, clampArrayRange } from "@antfu/utils";
// Generate ranges
const simple = range(5); // [0, 1, 2, 3, 4]
const withStart = range(2, 8); // [2, 3, 4, 5, 6, 7]
const withStep = range(0, 10, 2); // [0, 2, 4, 6, 8]
// Safe array indexing
const arr = ["a", "b", "c"];
const safeIndex = clampArrayRange(10, arr); // 2 (clamped to max valid index)Random operations and sampling from arrays.
/**
* Get random item(s) from an array
* @param arr - Array to sample from
* @param quantity - Number of random items to return
* @returns Array of randomly selected items
*/
function sample<T>(arr: T[], quantity: number): T[];
/**
* Shuffle an array. This function mutates the array.
* @param array - Array to shuffle (mutated)
* @returns The shuffled array
*/
function shuffle<T>(array: T[]): T[];Usage Examples:
import { sample, shuffle } from "@antfu/utils";
const colors = ["red", "green", "blue", "yellow", "purple"];
// Sample random items
const randomColors = sample(colors, 3); // e.g., ["blue", "red", "purple"]
// Shuffle array (mutates original)
shuffle(colors); // colors is now in random orderHigh-performance array operations for large datasets.
/**
* Filter out items from an array in place.
* This function mutates the array.
* `predicate` iterates through the array from end to start for performance.
*
* Expect this function to be faster than using `Array.prototype.filter` on large arrays.
* @param array - Array to filter (mutated)
* @param predicate - Filter predicate function
* @returns The filtered array
*/
function filterInPlace<T>(array: T[], predicate: (item: T, index: number, arr: T[]) => unknown): T[];Usage Examples:
import { filterInPlace } from "@antfu/utils";
// High-performance filtering for large arrays
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
filterInPlace(numbers, n => n % 2 === 0); // numbers is now [2, 4, 6, 8, 10]