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"

