or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

array.mdcompat.mderror.mdfunction.mdindex.mdmath.mdobject.mdpredicate.mdpromise.mdstring.mdutil.md
tile.json

array.mddocs/

Array Utilities

Comprehensive array manipulation functions optimized for performance with strong TypeScript type safety. These utilities cover array access, manipulation, set operations, transformation, and analysis.

Capabilities

Array Access and Selection

Functions for accessing and selecting elements from arrays with support for negative indices and random sampling.

/**
 * Retrieves elements from an array at specified indices
 * @param arr - The source array
 * @param indices - Array of indices (supports negative indices)
 * @returns New array with elements at specified indices
 */
function at<T>(arr: readonly T[], indices: number[]): T[];

/**
 * Gets the first element of an array
 * @param arr - The source array
 * @returns First element or undefined if array is empty
 */
function head<T>(arr: readonly T[]): T | undefined;

/**
 * Gets the last element of an array
 * @param arr - The source array  
 * @returns Last element or undefined if array is empty
 */
function last<T>(arr: readonly T[]): T | undefined;

/**
 * Gets all elements except the first one
 * @param arr - The source array
 * @returns New array with all but first element
 */
function tail<T>(arr: readonly T[]): T[];

/**
 * Gets all elements except the last one
 * @param arr - The source array
 * @returns New array with all but last element
 */
function initial<T>(arr: readonly T[]): T[];

/**
 * Gets a random element from the array
 * @param arr - The source array
 * @returns Random element or undefined if array is empty
 */
function sample<T>(arr: readonly T[]): T | undefined;

/**
 * Gets multiple random elements from the array
 * @param arr - The source array
 * @param size - Number of elements to sample
 * @returns Array of random elements
 */
function sampleSize<T>(arr: readonly T[], size: number): T[];

Usage Examples:

import { at, head, last, sample } from 'es-toolkit/array';

const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Access elements at specific indices
const selected = at(fruits, [0, 2, -1]);
console.log(selected); // ['apple', 'cherry', 'elderberry']

// Get first and last elements
console.log(head(fruits)); // 'apple'
console.log(last(fruits)); // 'elderberry'

// Random sampling
console.log(sample(fruits)); // random fruit like 'cherry'

Array Chunking and Splitting

Functions for dividing arrays into smaller pieces or creating chunks of specific sizes.

/**
 * Splits array into smaller arrays of specified length
 * @param arr - The source array
 * @param size - The length of each chunk (must be positive integer)
 * @returns 2D array of chunks
 * @throws Error if size is not a positive integer
 */
function chunk<T>(arr: readonly T[], size: number): T[][];

/**
 * Removes falsy values from array
 * @param arr - The source array
 * @returns New array with falsy values removed
 */
function compact<T>(arr: readonly T[]): Array<NotFalsey<T>>;

/**
 * Splits array into two groups based on predicate
 * @param arr - The source array
 * @param isInTruthy - Predicate function
 * @returns Tuple of [truthy elements, falsy elements]
 */
function partition<T>(arr: readonly T[], isInTruthy: (value: T) => boolean): [truthy: T[], falsy: T[]];

Usage Examples:

import { chunk, compact, partition } from 'es-toolkit/array';

// Chunk array into groups
const numbers = [1, 2, 3, 4, 5, 6, 7];
const chunks = chunk(numbers, 3);
console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7]]

// Remove falsy values
const mixed = [1, 0, 'hello', '', true, false, null, undefined];
const truthy = compact(mixed);
console.log(truthy); // [1, 'hello', true]

// Partition into groups
const users = [
  { name: 'Alice', active: true },
  { name: 'Bob', active: false },
  { name: 'Charlie', active: true }
];
const [active, inactive] = partition(users, user => user.active);

Array Manipulation

Functions for adding, removing, and transforming array elements while maintaining immutability where appropriate.

/**
 * Removes elements from the beginning of array
 * @param arr - The source array
 * @param itemsCount - Number of elements to remove
 * @returns New array with elements removed from start
 */
function drop<T>(arr: readonly T[], itemsCount: number): T[];

/**
 * Removes elements from the end of array
 * @param arr - The source array
 * @param itemsCount - Number of elements to remove
 * @returns New array with elements removed from end
 */
function dropRight<T>(arr: readonly T[], itemsCount: number): T[];

/**
 * Drops elements from start while predicate returns true
 * @param arr - The source array
 * @param shouldContinueDropping - Predicate function
 * @returns New array with elements dropped from start
 */
function dropWhile<T>(arr: readonly T[], shouldContinueDropping: (item: T) => boolean): T[];

/**
 * Takes first n elements from array
 * @param arr - The source array
 * @param count - Number of elements to take
 * @returns New array with first n elements
 */
function take<T>(arr: readonly T[], count: number): T[];

/**
 * Fills array with static value (mutating)
 * @param arr - The array to fill
 * @param value - The value to fill with
 * @param start - Start index (default: 0)
 * @param end - End index (default: array length)
 * @returns The modified array
 */
function fill<T, U>(arr: T[], value: U, start?: number, end?: number): Array<T | U>;

/**
 * Creates filled array without mutating original (non-mutating)
 * @param arr - The source array
 * @param value - The value to fill with
 * @param start - Start index (default: 0)
 * @param end - End index (default: array length)
 * @returns New filled array
 */
function toFilled<T, U>(arr: readonly T[], value: U, start?: number, end?: number): Array<T | U>;

/**
 * Randomly shuffles array elements
 * @param arr - The source array
 * @returns New array with shuffled elements
 */
function shuffle<T>(arr: readonly T[]): T[];

/**
 * Removes elements matching predicate (mutating)
 * @param arr - The array to modify
 * @param predicate - Function to test elements
 * @returns Array of removed elements
 */
function remove<T>(arr: T[], predicate: (item: T, index: number, arr: T[]) => boolean): T[];

/**
 * Removes specific values from array (mutating)
 * @param arr - The array to modify
 * @param valuesToRemove - Values to remove
 * @returns The modified array
 */
function pull<T>(arr: T[], ...valuesToRemove: T[]): T[];

/**
 * Creates array excluding specified values (non-mutating)
 * @param arr - The source array
 * @param values - Values to exclude
 * @returns New array without specified values
 */
function without<T>(arr: readonly T[], ...values: T[]): T[];

Set Operations

Mathematical set operations for arrays including union, intersection, and difference calculations.

/**
 * Creates array of values in first array but not in second
 * @param firstArr - Primary array
 * @param secondArr - Array of values to exclude
 * @returns Elements in first array but not in second
 */
function difference<T>(firstArr: readonly T[], secondArr: readonly T[]): T[];

/**
 * Difference with custom mapping function for comparison
 * @param firstArr - Primary array
 * @param secondArr - Array of values to exclude  
 * @param mapper - Function to map values for comparison
 * @returns Elements in first array but not in second (by mapped value)
 */
function differenceBy<T, U>(
  firstArr: readonly T[], 
  secondArr: readonly U[], 
  mapper: (item: T | U) => unknown
): T[];

/**
 * Creates array of shared values found in both arrays
 * @param firstArr - First array
 * @param secondArr - Second array
 * @returns Common elements from both arrays
 */
function intersection<T>(firstArr: readonly T[], secondArr: readonly T[]): T[];

/**
 * Creates array of unique values from all arrays
 * @param arrays - Arrays to union
 * @returns Combined array with duplicates removed
 */
function union<T>(...arrays: Array<readonly T[]>): T[];

/**
 * Creates duplicate-free version of array
 * @param arr - The source array
 * @returns New array with duplicates removed
 */
function uniq<T>(arr: readonly T[]): T[];

/**
 * Creates unique array based on mapped values
 * @param arr - The source array
 * @param mapper - Function to generate comparison values
 * @returns Array with duplicates removed (by mapped value)
 */
function uniqBy<T, U>(arr: readonly T[], mapper: (item: T) => U): T[];

/**
 * Creates symmetric difference of two arrays
 * @param arr1 - First array
 * @param arr2 - Second array
 * @returns Elements that exist in either array but not both
 */
function xor<T>(arr1: readonly T[], arr2: readonly T[]): T[];

/**
 * Checks if second array is subset of first
 * @param superset - Array that may contain all elements
 * @param subset - Array to check if contained
 * @returns True if subset is contained in superset
 */
function isSubset<T>(superset: readonly T[], subset: readonly T[]): boolean;

Usage Examples:

import { difference, intersection, union, uniq } from 'es-toolkit/array';

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

// Set operations
console.log(difference(arr1, arr2)); // [1, 2]
console.log(intersection(arr1, arr2)); // [3, 4, 5]  
console.log(union(arr1, arr2)); // [1, 2, 3, 4, 5, 6, 7]

// Remove duplicates
const duplicates = [1, 2, 2, 3, 3, 3, 4];
console.log(uniq(duplicates)); // [1, 2, 3, 4]

Array Grouping and Analysis

Functions for organizing, grouping, and analyzing array data based on custom criteria.

/**
 * Groups elements by key-generating function
 * @param arr - The source array
 * @param getKeyFromItem - Function to generate group keys
 * @returns Object with keys mapped to arrays of elements
 */
function groupBy<T, K extends PropertyKey>(
  arr: readonly T[], 
  getKeyFromItem: (item: T) => K
): Record<K, T[]>;

/**
 * Counts occurrences by key-generating function
 * @param arr - The source array
 * @param getKeyFromItem - Function to generate count keys
 * @returns Object with keys mapped to occurrence counts
 */
function countBy<T, K extends PropertyKey>(
  arr: readonly T[], 
  getKeyFromItem: (item: T) => K
): Record<K, number>;

/**
 * Creates object indexed by key-generating function
 * @param arr - The source array
 * @param getKeyFromItem - Function to generate object keys
 * @returns Object with keys mapped to corresponding elements
 */
function keyBy<T, K extends PropertyKey>(
  arr: readonly T[], 
  getKeyFromItem: (item: T) => K
): Record<K, T>;

Sorting and Ordering

Advanced sorting functions with support for multiple criteria and custom value extraction.

/**
 * Sorts array by multiple criteria with specified order directions
 * @param arr - The source array
 * @param criteria - Array of functions or property names for sorting
 * @param orders - Array of 'asc' or 'desc' for each criterion
 * @returns New sorted array
 */
function orderBy<T>(
  arr: readonly T[], 
  criteria: Array<((item: T) => unknown) | keyof T>, 
  orders: Array<'asc' | 'desc'>
): T[];

/**
 * Sorts array by computed keys
 * @param arr - The source array
 * @param getKeyFromItem - Function to compute sort keys
 * @returns New sorted array
 */
function sortBy<T>(arr: readonly T[], getKeyFromItem: (item: T) => unknown): T[];

/**
 * Finds element with maximum value by selector function
 * @param items - The source array
 * @param getValue - Function to extract comparison values
 * @returns Element with maximum value or undefined
 */
function maxBy<T>(items: readonly T[], getValue: (element: T) => number): T | undefined;

/**
 * Finds element with minimum value by selector function
 * @param items - The source array
 * @param getValue - Function to extract comparison values
 * @returns Element with minimum value or undefined
 */
function minBy<T>(items: readonly T[], getValue: (element: T) => number): T | undefined;

Array Transformation

Functions for transforming array structure including flattening and functional mapping operations.

/**
 * Maps each element and flattens result one level deep
 * @param arr - The source array
 * @param iteratee - Function to transform elements
 * @returns Flat array of transformed elements
 */
function flatMap<T, U>(
  arr: readonly T[], 
  iteratee: (item: T, index: number, arr: readonly T[]) => U | readonly U[]
): U[];

/**
 * Maps each element and flattens result completely
 * @param arr - The source array
 * @param iteratee - Function to transform elements
 * @returns Completely flat array of transformed elements
 */
function flatMapDeep<T, U>(
  arr: readonly T[], 
  iteratee: (item: T, index: number, arr: readonly T[]) => U | readonly U[]
): U[];

/**
 * Flattens array up to specified depth
 * @param arr - The source array
 * @param depth - Depth level to flatten (default: 1)
 * @returns Flattened array
 */
function flatten<T, D extends number = 1>(
  arr: readonly T[], 
  depth?: D
): Array<FlatArray<T[], D>>;

/**
 * Completely flattens nested arrays
 * @param arr - The source array
 * @returns Completely flat array
 */
function flattenDeep<T>(arr: readonly T[]): T[];

/**
 * Iterates over array elements from right to left
 * @param arr - The source array
 * @param callback - Function to execute for each element
 */
function forEachRight<T>(
  arr: readonly T[], 
  callback: (value: T, index: number, arr: readonly T[]) => void
): void;

Array Zipping

Functions for combining multiple arrays and creating object structures from array data.

/**
 * Combines multiple arrays into array of tuples
 * @param arrs - Arrays to combine
 * @returns Array of tuples with elements from each input array
 */
function zip<T>(...arrs: Array<readonly T[]>): T[][];

/**
 * Creates object from arrays of keys and values
 * @param keys - Array of property names
 * @param values - Array of property values
 * @returns Object with keys mapped to corresponding values
 */
function zipObject<K extends PropertyKey, V>(
  keys: readonly K[], 
  values: readonly V[]
): Record<K, V>;

/**
 * Combines arrays with transformation function
 * @param arr1 - First array
 * @param iteratee - Function to combine elements
 * @returns Array of transformed combinations
 */
function zipWith<T, R>(
  arr1: readonly T[], 
  iteratee: (item: T) => R
): R[];

/**
 * Separates zipped arrays back to individual arrays
 * @param arr - Array of tuples to separate
 * @returns Array of individual arrays
 */
function unzip<T>(arr: readonly T[][]): T[][];

/**
 * Unzips arrays with transformation function
 * @param arr - Array of tuples to process
 * @param iteratee - Function to transform separated elements
 * @returns Array of transformed results
 */
function unzipWith<T, R>(
  arr: readonly T[][], 
  iteratee: (...args: T[]) => R
): R[];

Advanced Array Operations

Specialized array operations for windowing and complex manipulations.

/**
 * Creates sliding windows of specified size
 * @param arr - The source array
 * @param size - Size of each window
 * @returns Array of sliding window arrays
 */
function windowed<T>(arr: readonly T[], size: number): T[][];

Usage Examples:

import { windowed, zip, zipObject, flatMap } from 'es-toolkit/array';

// Sliding windows
const data = [1, 2, 3, 4, 5];
const windows = windowed(data, 3);
console.log(windows); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

// Zipping arrays
const names = ['alice', 'bob', 'charlie'];
const ages = [25, 30, 35];
const users = zipObject(names, ages);
console.log(users); // { alice: 25, bob: 30, charlie: 35 }

// FlatMap transformation
const sentences = ['hello world', 'foo bar'];
const words = flatMap(sentences, sentence => sentence.split(' '));
console.log(words); // ['hello', 'world', 'foo', 'bar']

Key Types

/**
 * Type that excludes falsy values
 */
type NotFalsey<T> = Exclude<T, false | null | 0 | 0n | '' | undefined>;

/**
 * TypeScript built-in type for flattening arrays to specified depth
 */
type FlatArray<Arr, Depth extends number>;