Given a multi-dimensional array arr
and a depth n
, return a flattened version of that array.
A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n
. The depth of the elements in the first array are considered to be 0
.
Please solve it without the built-in Array.flat
method.
// 當 current depth of array < n 時,就會被 flattened
// 要再多判斷不是 array 的不用再被 flatten
var flat = function (arr, n) {
const newArray = [];
function flatten(ele, depth) {
if (depth < n && Array.isArray(ele)) {
for (let i = 0; i < ele.length; i++) {
flatten(ele[i], depth + 1);
}
} else {
newArray.push(ele);
}
}
for (let i = 0; i < arr.length; i++) {
flatten(arr[i], 0);
}
return newArray;
};
Recursion function
recursion 是指一個函式會在自己的定義中呼叫自己,直到滿足某個基礎條件(base condition)時才會停止。這個基礎條件的存在是為了終止遞迴。
舉例:列出所有物件裡的 children name
function printChildrenRecursive(t) {
if (t.children.length === 0) { // base condition
return;
}
t.children.forEach(c => {
console.log(c.name);
printChildrenRecursive(c);
});
}
const tree = {
name: 'John',
children: [
{ name: 'Jim', children: [] },
{
name: 'Kyle',
children: [
{ name: 'Denny', children: [] },
{ name: 'Nancy', children: [] },
],
},
],
};