| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | /** |
| 7 | | * @param {any[]} arr |
| 8 | | * @returns {any[]} |
| 7 | * Flattens a nested array of any depth into a single-level array, 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 | * @example |
| 13 | * flatten([1, [2, 6, null], [[null, [4]], 5]]) |
| 14 | * // returns [1, 2, 6, 4, 5] |
| 15 | * |
| 16 | * @example |
| 17 | * flatten([1, [2, [3, [4, [5]]]]]) |
| 18 | * // returns [1, 2, 3, 4, 5] |
| 19 | * |
| 20 | * @example |
| 21 | * flatten([null, [undefined, [1, 2]], 3]) |
| 22 | * // returns [1, 2, 3] |
| 9 | 23 | */ |
| 10 | 24 | export const flatten = (arr) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 12 | | }; |
| 25 | // Edge Case: Handle when input is not an array |
| 26 | if (!Array.isArray(arr)) { |
| 27 | return []; |
| 28 | } |
| 29 | |
| 30 | const result = []; |
| 31 | |
| 32 | for (const item of arr) { |
| 33 | // Edge Case: Skip null and undefined values |
| 34 | if (item === null || item === undefined) { |
| 35 | continue; |
| 36 | } |
| 37 | |
| 38 | // Edge Case: If item is an array, recursively flatten it and push each element to result |
| 39 | if (Array.isArray(item)) { |
| 40 | const flattened = flatten(item); |
| 41 | result.push(...flattened); |
| 42 | } else { |
| 43 | // Edge Case: If item is a primitive value, push it directly to result |
| 44 | result.push(item); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | return result; |
| 49 | |
| 50 | // Handled Edge Cases: |
| 51 | // 1. Input is not an array |
| 52 | // 2. Null values in the array |
| 53 | // 3. Undefined values in the array |
| 54 | // 4. Nested arrays of any depth |
| 55 | // 5. Mixed data types in the array |
| 56 | // 6. Empty arrays |
| 57 | }; |