apps-script-utils 2.1.1 Help

compact

function compact<T>(array: Array<T | Falsy>): T[];

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

array

Array<T \| Falsy>

Falsy>`

Returns

T[] — a new array holding only the truthy values, in their original order.

Throws

Exception

Condition

TypeError

array is not an array.

Examples

Dropping the falsy values

compact([0, 1, false, 2, "", 3, null]); // => [1, 2, 3] compact([NaN, undefined]); // => [] compact([0, ""]); // => [] — both are falsy

Reading a column without the blanks

The column arrives as Array<string | null> and leaves as string[], with no cast in between.

/** * Reads a column of identifiers and drops the blanks, without a cast: * `compact` returns `string[]`, not `Array<string | null>`. */ export function readIds(sheet: GoogleAppsScript.Spreadsheet.Sheet): string[] { const column = sheet.getRange("A2:A").getValues().flat() as Array<string | null>; return compact(column); }
function readIds(sheet) { const column = sheet.getRange("A2:A").getValues().flat(); return compact(column); }

When nonNil is the better filter

import { nonNil } from "apps-script-utils"; const cells = [0, "", 5, null]; // a column read from a sheet compact(cells); // => [5] — drops the legitimate 0 and the empty cell cells.filter(nonNil); // => [0, "", 5] — drops only the absent values

See also

Source

src/lang/array/compact.ts

23 September 2026

This documentation was generated with AI (Claude) from the library's source code.