Last active
May 31, 2024 16:04
-
-
Save essejmclean/650f6e62fa56de9255f3fa7afb0a6c15 to your computer and use it in GitHub Desktop.
Filters out null and undefined values from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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