Flattening Multi-Dimensional Arrays in JavaScript: A Simple Approach
DescriptionThis solution provides a straightforward way to flatten multi-dimensional arrays in JavaScript based on a specified depth. It is designed for beginne
# Description
This solution provides a straightforward way to flatten `multi-dimensional arrays` in JavaScript based on a `specified depth`. It is designed for beginners and explains the logic behind the code` step-by-step`.
# Code Explanation 
1. **Function Declaration**: The main function flat takes two parameters:
`arr`: The multi-dimensional array you want to flatten.
`maxDepth`: The maximum depth to which the array should be flattened.
2. **Final Result Array**: An empty array `finalResult` is initialized to store the flattened elements.
3. **Helper Function**:A nested function `flattenHelper` is defined to perform the actual flattening. This function takes two parameters:
`sub_arr`: The current sub-array being processed.
`depth`: The current depth of the recursion.
4.**Iterating Through the Array:** The ``forEach`` method is used to loop through each item in the `sub_arr`. For each item
   - Check if the Item is an Array: If the item is an array and the current `depth` is less than `maxDepth`, the function calls itself recursively with the item and an increased depth `(depth + 1)`.
   - `This allows the function to dive deeper into the nested arrays.`
   - Pushing Non-Array Items If the item is not an array or the current `depth` has reached `maxDepth`, the item is pushed directly into `finalResult`

# Find Me : 
- Portfolio Link: https://raed-almasri.netlify.app/ 
# Example Usage
```javascript []
// /**
//  * @param {Array} arr
//  * @param {number} depth
//  * @return {Array}
//  */

var flat = function (arr, maxDepth) {
    let finalResult = [];
    function flattenHelper (sub_arr, depth) {
        sub_arr.forEach(item =>
            // Note: You should use depth + 1, not depth++,
            // because depth++ means you increase the current depth and then pass it to the recursive function.
            // However, we should not do that because the current level should not be affected.
            // that is take me some time to know that bug , however the problem must be easy level  
            Array.isArray(item) && depth < maxDepth ? flattenHelper(item, depth + 1) : finalResult.push(item)
        );
    };
    flattenHelper(arr, 0);
    return finalResult;
};
 
```
['JavaScript']