| 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 all 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 | * - Non-array inputs (returns empty array) | |
| 9 | 18 | */ |
| 10 | 19 | export const flatten = (arr) => { |
| 11 | throw new Error('Remove this line and implement the function'); | |
| 20 | // Edge Case: Handle non-array inputs | |
| 21 | if (!Array.isArray(arr)) { | |
| 22 | return []; | |
| 23 | } | |
| 24 | ||
| 25 | const result = []; | |
| 26 | ||
| 27 | for (let i = 0; i < arr.length; i++) { | |
| 28 | const element = arr[i]; | |
| 29 | ||
| 30 | // Edge Case: Skip null and undefined values | |
| 31 | if (element === null || element === undefined) { | |
| 32 | continue; | |
| 33 | } | |
| 34 | ||
| 35 | // Edge Case: Recursively flatten nested arrays | |
| 36 | if (Array.isArray(element)) { | |
| 37 | const flattened = flatten(element); | |
| 38 | result.push(...flattened); | |
| 39 | } else { | |
| 40 | result.push(element); | |
| 41 | } | |
| 42 | } | |
| 43 | ||
| 44 | return result; | |
| 12 | 45 | }; |
| 46 | ||
| 47 | // Handled Edge Cases: Non-array inputs, null/undefined values, nested arrays, empty arrays |