🧹 Removes all falsy (opens in a new tab) values from an array.
✅
Immutable: This function does not mutate the original array.
Syntax
import { compact } from '@opentf/std';
compact<T>(arr: T[] = []): Partial<T[]>Parameters
arr: The source array.
Returns
A new array with all falsy values removed.
Falsy Values
A falsy value is a value that is considered false when encountered in a Boolean context. In JavaScript, there are only 8 falsy values:
| Value | Description |
|---|---|
false | The keyword false. |
0 | The number zero. |
-0 | The number negative zero. |
0n | The BigInt zero. |
"" | An empty string. |
null | The absence of any object value. |
undefined | A primitive value for uninitialized variables. |
NaN | Not-a-Number. |
Everything else is truthy, including empty objects {} and empty arrays [].
Examples
compact([0, 1, false, 2, '', 3, null, undefined, NaN]) //=> [1, 2, 3]
compact(['apple', '', 'Mango']) //=> ['apple', 'Mango']
compact([{}, []]) //=> [{}, []] (Empty objects and arrays are truthy)