compact

Removes falsy values from an array, If extend is true, also removes empty objects and arrays.

1.
/**
2.
* Removes falsy values from an array, If extend is true, also removes empty objects and arrays.
3.
**/
4.
const compact = <T,>(array: T[], extend: boolean = false): T[] => {
5.
let truthy = array.filter((item) => {
6.
// remove all falsy values and excluded values
7.
return Boolean(item);
8.
});
9.
10.
if (extend) {
11.
// remove all empty objects
12.
truthy = truthy.filter((item) => {
13.
if (typeof item === 'object' && !(item instanceof Array)) {
14.
return Object.keys(item as object).length > 0;
15.
}
16.
return true;
17.
});
18.
// remove all empty arrays
19.
truthy = truthy.filter((item) => {
20.
if (Array.isArray(item)) {
21.
return (item as []).length > 0;
22.
}
23.
return true;
24.
});
25.
}
26.
return truthy;
27.
};
28.
29.
export default compact;

1. Installtion

npx @jrtilak/lazykit add compact

2. Parameters

  • array (T[])
    The array from which to remove falsy values. The function iterates over this array to filter out the unwanted elements.

  • extend (optional) (boolean)
    A flag that determines whether to remove empty objects and arrays in addition to falsy values. Defaults to false.

3. Returns

  • T[]
    Returns a new array containing only the truthy values from the original array. If extend is true, it also excludes empty objects and arrays.

4. Type Parameters

  • T
    The type of elements in the array. This allows the function to work with arrays of any type, ensuring type safety for the filtered elements.

5. Usage

1. Basic Usage

1.
import compact from '@/helpers/compact';
2.
3.
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, {}, [], [4, 5]];
4.
const result = compact(mixedArray);
5.
6.
console.log(result);
7.
// Output: [1, 2, 3, {}, [], [4, 5]]

2. Using the extend Option

1.
import compact from '@/helpers/compact';
2.
3.
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, {}, [], [4, 5]];
4.
const result = compact(mixedArray, true);
5.
6.
console.log(result);
7.
// Output: [1, 2, 3, [4, 5]]