|
| 1 | +```js |
| 2 | +/** |
| 3 | + * Flattens a nested array into a single-level array. |
| 4 | + * |
| 5 | + * @param {Array} array - The array to flatten. |
| 6 | + * @returns {Array} - A new array with all sub-array elements flattened. |
| 7 | + */ |
| 8 | +function flatten(array) { |
| 9 | + // Validate input to ensure it's an array |
| 10 | + if (!Array.isArray(array)) { |
| 11 | + throw new TypeError('Expected an array'); |
| 12 | + } |
| 13 | + |
| 14 | + const result = []; // Create a new array to store the flattened elements |
| 15 | + |
| 16 | + // Helper function to recursively flatten the array |
| 17 | + function recursiveFlatten(arr) { |
| 18 | + for (let i = 0; i < arr.length; i++) { |
| 19 | + const item = arr[i]; |
| 20 | + if (Array.isArray(item)) { |
| 21 | + // If the item is an array, recurse into it |
| 22 | + recursiveFlatten(item); |
| 23 | + } else { |
| 24 | + // If it's not an array, push it to the result |
| 25 | + result.push(item); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + recursiveFlatten(array); // Start the recursive flattening |
| 31 | + return result; // Return the flattened array |
| 32 | +} |
| 33 | + |
| 34 | +export default flatten; |
| 35 | +``` |
| 36 | +### Explanation |
| 37 | +#### Validate Input: |
| 38 | +The function verifies that the input array is indeed an array using Array.isArray and throws an error if it's not. |
| 39 | + |
| 40 | +#### Create a result Array: |
| 41 | +A new array (result) is created to store the flattened elements. This ensures that the original input array remains unchanged (pure function). |
| 42 | + |
| 43 | +#### Recursive Helper Function: |
| 44 | +A recursive helper function, recursiveFlatten, is defined to iterate through the array: |
| 45 | + |
| 46 | +* If an element is an array (Array.isArray(item)), the function recursively calls itself with the sub-array. |
| 47 | +* If the element is not an array, it is directly pushed into the result array. |
| 48 | +#### Return the Result: |
| 49 | +After the recursive flattening is complete, the result array is returned. |
0 commit comments