compact
Removes elements from an array that do not pass the predicate function. If no predicate is provided, removes all falsy values.
1/**
2 * Removes elements from an array that do not pass the predicate function.
3 * If no predicate is provided, removes all falsy values.
4 *
5 * @param arr - The array to filter.
6 * @param predicate - Optional custom predicate function.
7 * @returns A new filtered array.
8 */
9export function compact<T>(arr: T[], predicate: (value: T) => boolean = Boolean): T[] {
10 return arr.filter(predicate);
11}
Flexible predicate support
Allows filtering based on a custom predicate, enabling a wide range of use cases beyond just removing falsy values.
Default behavior matches Lodash-style compact
When no predicate is provided, it removes all falsy values (
false
,0
,''
,null
,undefined
,NaN
) — a common utility in data cleanup.Non-mutating
Returns a new array, leaving the original untouched, which supports functional programming best practices.
Short and performant
Leverages native
.filter()
for efficient execution with minimal overhead.Readable and concise
Simple signature and intuitive behavior make it easy to adopt in any codebase.
Tests | Examples
1test('compact removes default falsy values', () => {
2 expect(compact([0, 1, false, 2, '', 3])).toEqual([1, 2, 3]);
3 expect(compact(['a', '', 'b', null, 'c'])).toEqual(['a', 'b', 'c']);
4});
5
6test('compact with custom predicate', () => {
7 expect(compact([1, 2, 3, 4, 5], n => n > 2)).toEqual([3, 4, 5]);
8 expect(compact(['cat', 'dog', ''], str => str.length > 0)).toEqual(['cat', 'dog']);
9 expect(compact([{ ok: true }, { ok: false }], item => item.ok)).toEqual([{ ok: true }]);
10});
Common Use Cases
Cleaning user input or form data
Remove empty strings,
null
, orundefined
values from user-submitted arrays.Filtering optional values
Eliminate placeholder values from datasets (e.g.,
[1, '', 2, null] → [1, 2]
).Custom filtering
Use with a predicate like
(x) => x > 0
or(x) => typeof x === 'string'
for domain-specific cleanup.React or UI rendering
Clean up arrays before rendering to avoid passing invalid or empty content into components.
Preparing data for export or APIs
Filter out unnecessary or incomplete records before sending data to a server or displaying in a report.