apps-script-utils (Deutsch) 2.1.1 Help

compact

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

compact verwirft false, null, undefined, 0, -0, 0n, "" und NaN und gibt den Rest als neues Array zurück. Die Eingabe bleibt unverändert.

Der Gewinn gegenüber array.filter(Boolean) liegt im Typ: TypeScript behält dort den ursprünglichen Elementtyp, sodass der Aufrufer die null anschließend selbst wegcasten muss. compact liefert T[] ohne Cast.

Beachten Sie, dass auch 0 und "" als falsy gelten. Für Tabellendaten ist das meist das falsche Werkzeug — 0 ist eine gültige Zahl und eine leere Zelle kommt als "" an — dort entfernt array.filter(nonNil) nur die fehlenden Werte.

Parameter

Parameter

Typ

Beschreibung

array

Array<T \| Falsy>

Das zu bereinigende Array. Bleibt unverändert.

Rückgabewert

T[] — ein neues Array nur mit den truthy-Werten, in ursprünglicher Reihenfolge.

Ausnahmen

Ausnahme

Bedingung

TypeError

array ist kein Array.

Beispiele

Die falsy-Werte verwerfen

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

Eine Spalte ohne leere Zellen lesen

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); }

Wann nonNil der bessere Filter ist

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

Siehe auch

Quellcode

src/lang/array/compact.ts

23 September 2026

Diese Dokumentation wurde mit KI (Claude) aus dem Quellcode der Bibliothek erzeugt.