Skip to content

compact

Removes all falsy values (false, null, undefined, 0, "", NaN) from an array. null and undefined are treated as empty arrays and return [].

Available since v2.0.0

import { compact } from '@helpers4/array';
compact<T>(array: readonly Falsy | T[] | null | undefined): Exclude<T, Falsy>[]
ParameterTypeDescription
arrayreadonly Falsy | T[] | null | undefinedThe array to compact

Exclude<T, Falsy>[] — A new array with only truthy values

Removes all falsy values (false, null, undefined, 0, "", NaN) from an array.

compact([0, 1, false, 2, '', 3, null, undefined, NaN])
// => [1, 2, 3]

Useful to clean up arrays with null/undefined gaps.

compact(['hello', null, 'world', undefined, ''])
// => ['hello', 'world']

View source on GitHub