| 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 | * @param {any[]} arr - The nested array to flatten | |
| 9 | * @returns {any[]} - A flattened array with no nested arrays and no null/undefined values | |
| 9 | 10 | */ |
| 10 | 11 | export const flatten = (arr) => { |
| 11 | throw new Error('Remove this line and implement the function'); | |
| 12 | // Edge Case: Input is not an array - return empty array | |
| 13 | if (!Array.isArray(arr)) { | |
| 14 | return []; | |
| 15 | } | |
| 16 | ||
| 17 | const result = []; | |
| 18 | ||
| 19 | for (const item of arr) { | |
| 20 | // Edge Case: Skip null and undefined values | |
| 21 | if (item === null || item === undefined) { | |
| 22 | continue; | |
| 23 | } | |
| 24 | ||
| 25 | // Edge Case: Item is an array - recursively flatten it | |
| 26 | if (Array.isArray(item)) { | |
| 27 | const flattened = flatten(item); | |
| 28 | result.push(...flattened); | |
| 29 | } else { | |
| 30 | // Edge Case: Item is a primitive value - add it to result | |
| 31 | result.push(item); | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | return result; | |
| 12 | 36 | }; |
| 37 | ||
| 38 | // Handled Edge Cases: Input is not an array, null values, undefined values, nested arrays of any depth, primitive values |