compact()
compact<
T>(array):Exclude<T,false|""|0|0n|null|undefined>[]
Removes all falsy values from an array.
💎 Why is this a Hidden Gem?
The most elegant idiom for cleaning arrays of falsy values.
Use array.filter(Boolean) directly instead.
Reason:
Native equivalent method now available
Type Parameters
T: T
The type of elements in the array.
Parameters
array: readonly T[]
The array to compact.
Returns: Exclude<T, false | "" | 0 | 0n | null | undefined>[]
A new array with all falsy values removed.
See Also
Since
2.0.0
Also known as
compact (Lodash, es-toolkit, Remeda) · getSomes (Effect) · sift (Radashi) · ❌ (Ramda, Modern Dash, Antfu)
Example
const mixed = [1, 0, false, '', 'hello', null, undefined];
// ❌ Deprecated approach
const compacted = compact(mixed);
console.log(compacted); // [1, 'hello']
// ✅ Recommended approach
const filtered = mixed.filter(Boolean);
console.log(filtered); // [1, 'hello']
How it works?
Removes all falsy values from an array.
Deprecated: Use array.filter(Boolean) directly.
Falsy Values Removed
| Value | Kept? |
|---|---|
0 | ![]() |
false | ![]() |
'' | ![]() |
null | ![]() |
undefined | ![]() |
NaN | ![]() |
1, 2, 3 | ![]() |
Native Equivalent
// ❌ compact(arr)
// ✅ arr.filter(Boolean)
Use Cases
Clean API responses with missing data 📌
Remove null and undefined values from API responses.
const apiUsers = [user1, null, user2, undefined, user3];
const validUsers = apiUsers.filter(Boolean);
// => [user1, user2, user3]
Filter optional form fields before submission
Remove empty or undefined values from form data.
const formValues = ["john@example.com", "", "John Doe", null];
formValues.filter(Boolean);
// => ["john@example.com", "John Doe"]
Clean Promise.allSettled results
Filter out rejected promises to get only successful values.
const values = results.map(r => r.status === "fulfilled" ? r.value : null);
values.filter(Boolean);
// => [user1, user3]
Build conditional CSS class lists
Construct a class string from conditional values, removing falsy entries.
The classic classNames pattern used in virtually every React/Vue project.
const isActive = true;
const isDisabled = false;
const hasError = true;
const classes = compact([
"btn",
isActive && "btn-active",
isDisabled && "btn-disabled",
hasError && "btn-error",
]).join(" ");
// => "btn btn-active btn-error"

