compact
arrays
Creates an array with all falsy values removed. The values false, null, 0, "", undefined, and NaN are falsy.
Installation
Import
import { compact } from '@tulx/utils';Source Code
Implementation
/**
* Creates an array with all falsy values removed.
* The values false, null, 0, "", undefined, and NaN are falsy.
*
* @param array - The array to compact.
* @returns The new array of filtered values.
*
* @example
* ```ts
* compact([0, 1, false, 2, '', 3]); // [1, 2, 3]
* ```
*/
export function compact<T>(array: readonly T[]): Array<NonNullable<T>> {
const result: Array<NonNullable<T>> = [];
const len = array.length;
for (let i = 0; i < len; i++) {
const item = array[i];
// Optimized order: most common cases first
if (item === null || item === undefined || item === false) {
continue;
}
if (item === 0 || item === '') {
continue;
}
if (Number.isNaN(item)) {
continue;
}
result.push(item as NonNullable<T>);
}
return result;
}
Example
import { compact } from '@tulx/utils';
compact([0, 1, false, 2, '', 3]); // [1, 2, 3]Related Functions
chunk
Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.
concat
Creates a new array concatenating array with any additional arrays and/or values.
difference
Creates an array of array values not included in the other given arrays. The order and references of result values are determined by the first array.
differenceBy
This method is like difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared.
differenceWith
This method is like difference except that it accepts comparator which is invoked to compare elements of array to values.
drop
Creates a slice of array with n elements dropped from the beginning.