Topic Description

Given a multidimensional array arr and a depth value n, return the flattened version of this array. A multidimensional array is a recursive data structure that can contain integers or other multidimensional arrays. Flattening an array means removing some or all sub-arrays and replacing them with their actual elements. This flattening operation is only performed when the current nested depth is less than n. The depth of elements in the first level of the array is considered 0.

// Example

Input:
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 0

Output:
[1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]

Explanation:
When the depth value n=0 is passed in, the original array is always returned as the output. This is because the minimum possible depth of the sub-arrays (0) is not less than n=0. Therefore, no sub-arrays are flattened.

Answer

function flattenArray(array, depth = Infinity){
	return array.flat(depth)
}

let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];
function flattenAllArray(array, resultArr=[]){

	for (const item of array) {
		if(Array.isArray(item)){
			flattenAllArray(item, resultArr)
		}else{
			resultArr.push(item)
		}
	}
	
	return resultArr
}

flattenAllArray(array)
let array = [1, 2, [3, [4, 5, [6, 7, [8]]]]];

function flattenArray(arr, n){
	const resultArray = []
	
	for (const item of arr) {
		if(Array.isArray(item) && n > 0){
			resultArray.push(...flattenArray(item, n - 1))
		}else{
			resultArray.push(item)
		}
	}
	
	return resultArray
}

flattenArray(array,2)