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"

