compact
EditReturns the truthy values from an array while preserving their order.
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;};Download
Section titled “Download”wget -O src/lib/compact.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/compact.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/compact.ts" src/lib/compact.ts && rm -r "$temp_dir"Examples
Section titled “Examples”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]]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 asfalse,0,0n,"",null,undefined, andNaNare removed.
Returns
Section titled “Returns”Array<Exclude<T, Falsy>> — A new array containing the truthy values.