| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | /** |
| 7 | | * @param {any[]} arr |
| 8 | | * @returns {any[]} |
| 7 | * Flattens a nested array of any depth, excluding null and undefined values. |
| 8 | * |
| 9 | * @param {any[]} arr - The nested array to flatten |
| 10 | * @returns {any[]} - A flattened array with null and undefined values removed |
| 11 | * |
| 12 | * Edge Cases Handled: |
| 13 | * - Empty arrays |
| 14 | * - Arrays with only null/undefined values |
| 15 | * - Deeply nested arrays |
| 16 | * - Mixed data types |
| 17 | * - Null and undefined values at any level |
| 9 | 18 | */ |
| 10 | 19 | export const flatten = (arr) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 12 | | }; |
| 20 | // Edge Case: Input is not an array |
| 21 | if (!Array.isArray(arr)) { |
| 22 | return []; |
| 23 | } |
| 24 | |
| 25 | const result = []; |
| 26 | |
| 27 | // Recursive helper function to process elements |
| 28 | const processElement = (element) => { |
| 29 | // Edge Case: Element is null or undefined |
| 30 | if (element === null || element === undefined) { |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | // Edge Case: Element is an array, need to process recursively |
| 35 | if (Array.isArray(element)) { |
| 36 | for (let i = 0; i < element.length; i++) { |
| 37 | processElement(element[i]); |
| 38 | } |
| 39 | } else { |
| 40 | // Edge Case: Element is a valid value |
| 41 | result.push(element); |
| 42 | } |
| 43 | }; |
| 44 | |
| 45 | // Process each element in the input array |
| 46 | for (let i = 0; i < arr.length; i++) { |
| 47 | processElement(arr[i]); |
| 48 | } |
| 49 | |
| 50 | return result; |
| 51 | |
| 52 | // Handled Edge Cases: Input is not an array, Empty arrays, Arrays with only null/undefined values, |
| 53 | // Deeply nested arrays, Mixed data types, Null and undefined values at any level |
| 54 | }; |