| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | /** |
| 7 | | * @param {any[]} arr |
| 8 | | * @returns {any[]} |
| 7 | * Flattens a nested array of any depth, excluding null-like values. |
| 8 | * |
| 9 | * @param {any[]} arr - The nested array to flatten |
| 10 | * @returns {any[]} - A flattened array with all null-like values removed |
| 9 | 11 | */ |
| 10 | 12 | export const flatten = (arr) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 13 | // Edge Case: Handle when input is not an array |
| 14 | if (!Array.isArray(arr)) { |
| 15 | return []; |
| 16 | } |
| 17 | |
| 18 | const result = []; |
| 19 | |
| 20 | for (let i = 0; i < arr.length; i++) { |
| 21 | const element = arr[i]; |
| 22 | |
| 23 | // Edge Case: Skip null-like values (null, undefined, NaN) |
| 24 | if (element === null || element === undefined || (typeof element === 'number' && isNaN(element))) { |
| 25 | continue; |
| 26 | } |
| 27 | |
| 28 | // Edge Case: Recursively flatten nested arrays |
| 29 | if (Array.isArray(element)) { |
| 30 | const flattened = flatten(element); |
| 31 | for (let j = 0; j < flattened.length; j++) { |
| 32 | result.push(flattened[j]); |
| 33 | } |
| 34 | } else { |
| 35 | result.push(element); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | return result; |
| 12 | 40 | }; |
| 41 | |
| 42 | // Handled Edge Cases: Input is not an array, null values, undefined values, NaN values, nested arrays of any depth |