compact
compact drops false, null, undefined, 0, -0, 0n, "" and NaN, and returns what is left in a new array. The input is not modified.
The point of the function over a plain array.filter(Boolean) is the type: TypeScript keeps the original element type through filter(Boolean), so the caller has to assert the nulls away afterwards. compact returns T[] without a cast.
Note that 0 and "" count as falsy. For values read out of a spreadsheet that is usually the wrong tool — 0 is a legitimate number and an empty cell arrives as "" — and array.filter(nonNil) removes only the absent values.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| Falsy>` |
Returns
T[] — a new array holding only the truthy values, in their original order.
Throws
Exception | Condition |
|---|---|
|
|
Examples
Dropping the falsy values
Reading a column without the blanks
The column arrives as Array<string | null> and leaves as string[], with no cast in between.
When nonNil is the better filter
See also
without— removes the values you name, rather than the falsy ones.
Source
This documentation was generated with AI (Claude) from the library's source code.