Skip to content

Instantly share code, notes, and snippets.

@essejmclean
Last active May 31, 2024 16:04
Show Gist options
  • Save essejmclean/650f6e62fa56de9255f3fa7afb0a6c15 to your computer and use it in GitHub Desktop.
Save essejmclean/650f6e62fa56de9255f3fa7afb0a6c15 to your computer and use it in GitHub Desktop.
Filters out null and undefined values from an array
/**
* Filters out null and undefined values from an array.
*
* @template T - The type of the array elements.
* @param {Array<T | null | undefined>} arr - The array to be filtered.
* @returns {Array<T>} - A new array with null and undefined values removed.
*
* @example
* const fruits = ['apple', null, 'banana', undefined, 'cherry'];
* const validFruits = filterEmpty(fruits);
* console.log(validFruits); // Output: ['apple', 'banana', 'cherry']
*/
export function filterEmpty<T>(arr: Array<T | null | undefined>): Array<T> {
return arr.flatMap((item) => (item != null ? [item] : []));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment