My first attempt at using recursion. The idea is to keep decreasing n
until 0 or less than 0. And during each iteration, each element in the array arr
is checked, if the element is an array, then all elements of the array element are pushed into the array newArr
, otherwise only push the element (which is a number
) into the array newArr
.
var flat = function (arr, n) {
const flatArr = (arr, n) => {
if(n <= 0) return arr;
const newArr = [];
for(let el of arr){
if(Array.isArray(el)) newArr.push(...el);
else newArr.push(el);
}
return flatArr(newArr, n-1)
}
return flatArr(arr, n);
};
The above solution passes 3 default test cases, but when the number n
of test cases is very large (i.e. 1000), a Runtime Error occurs.
arr:
[[2],[1],[1],[0],[1],[0],[0],[0],[1],[2],[3],[3],[2],[4],[0],[3],[1],[4],[1],[3],[3],[3],[4],[4],[4],[0],[1],[2],[4],[1],[2],[3],[1],[1],[3],[0],[4],[4], ...
n:
1000
Therefore, I added a new flag hasMoreSubArr
to check if any element currently in arr is an array instead of a number. When the current array arr
is a one-dimensional array, the function flatArr
will return the latest processed array newArr
instead of continuing the recursion.
var flat = function (arr, n) {
const flatArr = (arr, n) => {
if(n <= 0) return arr;
const newArr = [];
let hasMoreSubArr = false;
for(let el of arr){
if(Array.isArray(el)) {
hasMoreSubArr = true;
newArr.push(...el);
}
else newArr.push(el);
}
if(hasMoreSubArr) return flatArr(newArr, n-1);
else return newArr;
}
return flatArr(arr, n);
};
Top comments (0)