compact
Removes falsy values from an array, If strict is true, also removes empty objects and arrays.
1. Code
/**
* Removes falsy values
* Also removes empty objects and arrays if strict is true
*
* @template T - The type of elements in the array.
* @param {T[]} array - The array to compact.
* @param {boolean} [strict=false] - If true, also removes empty objects and arrays.
* @returns {T[]} - The compacted array.
*/
const compact = <T>(array: T[], strict: boolean = false): T[] => {
let truthy = array.filter((item) => {
// remove all falsy values and excluded values
return Boolean(item);
});
if (strict) {
// remove all empty objects
truthy = truthy.filter((item) => {
if (typeof item === "object" && !(item instanceof Array)) {
return Object.keys(item as object).length > 0;
}
return true;
});
// remove all empty arrays
truthy = truthy.filter((item) => {
if (Array.isArray(item)) {
return (item as []).length > 0;
}
return true;
});
}
return truthy;
};
export default compact;
2. Installation
npx @jrtilak/lazykit@latest add compact -undefined
3. Description
The compact function is a utility function in TypeScript that removes 'falsy' values from an array.
Falsy values in JavaScript are values that are considered false when encountered in a Boolean context. These include false, 0, '' (empty string), null, undefined, and NaN.
The function takes two parameters: an array of any type (array) and a boolean (strict). If the strict parameter is set to true, the function also removes empty objects and arrays from the array. An empty object is an object without any properties, and an empty array is an array without any elements. The function returns a new array that contains only 'truthy' values, and if strict is true, it also doesn't contain any empty objects or arrays.
4. Props
Prop
Type
Default Value
5. Examples
import compact from ".";
const input = [0, false, "", null, undefined, NaN, {}, [], 1, "hello"];
// no strict mode
const result = compact(input);
console.log(result);
// Expected output: [{}, [], 1, "hello"]
// strict mode
const resultStrict = compact(input, true);
console.log(resultStrict);
// Expected output: [1, "hello"]