Array
compact

🧹 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:

ValueDescription
falseThe keyword false.
0The number zero.
-0The number negative zero.
0nThe BigInt zero.
""An empty string.
nullThe absence of any object value.
undefinedA primitive value for uninitialized variables.
NaNNot-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)

Related

Try