For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/array/compact.md.

compact es-toolkit

Returns a new array with falsy values removed.

const compacted = compact(arr);

Usage

compact(arr)

Use compact when you want to remove falsy values (false, null, 0, -0, 0n, '', undefined, NaN) from an array. A new array containing only truthy values is returned.

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

// Remove various falsy values.
compact([0, -0, 0n, 1, false, 2, '', 3, null, undefined, 4, NaN, 5]);
// Returns: [1, 2, 3, 4, 5]

// Remove empty strings from a string array.
compact(['hello', '', 'world', '', '!']);
// Returns: ['hello', 'world', '!']

The type system automatically excludes falsy types.

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

const mixed: (string | number | false | null)[] = ['text', 0, false, null, 5];
const result = compact(mixed);
// result's type is (string | number)[]

Parameters

arrT[]required

The array to remove falsy values from.

Returns

A new array with falsy values removed.

Array<Exclude<T, false | null | 0 | 0n | '' | undefined>>
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.