#2625. Flatten Deeply Nested Array
Recursion 經典題, flat the array. 也是實現 arr.flat(n)
Last updated
Was this helpful?
Recursion 經典題, flat the array. 也是實現 arr.flat(n)
Last updated
Was this helpful?
Was this helpful?
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
var flat = function (arr, n) {
if(n==0) return arr
let result = [];
function flatArr(arr, n){
for(let val of arr){
if(n>0 && typeof val === "object"){
flatArr(val, n-1);
} else {
result.push(val)
}
}
}
flatArr(arr, n);
return result
};