Skip to content

compact

Edit

Returns the truthy values from an array while preserving their order.

compact.ts
export type Falsy = false | 0 | 0n | "" | null | undefined;
const isTruthy = <Value>(value: Value): value is Exclude<Value, Falsy> =>
Boolean(value);
/** Returns a new array containing only truthy values. */
export const compact = <const T>(
array: readonly T[],
): Array<Exclude<T, Falsy>> => {
const result: Array<Exclude<T, Falsy>> = [];
for (let index = 0; index < array.length; index += 1) {
if (!Object.hasOwn(array, index)) continue;
const value = array[index] as T;
if (isTruthy(value)) result.push(value);
}
return result;
};
Terminal
wget -O src/lib/compact.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/compact.ts
compact.example.ts
import { compact } from "./compact";
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, {}, [], [4, 5]];
const result = compact(mixedArray);
console.log(result);
// Output: [1, 2, 3, {}, [], [4, 5]]
compact.2.example.ts
import { compact } from "./compact";
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, {}, [], [4, 5]];
const result = compact(mixedArray);
console.log(result);
// Output: [1, 2, 3, {}, [], [4, 5]]
  • array (readonly T[]) — Values to filter. Empty slots and JavaScript falsy values such as false, 0, 0n, "", null, undefined, and NaN are removed.

Array<Exclude<T, Falsy>> — A new array containing the truthy values.