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