pleases describe me recursion function how to happen flatten array in the final result. Mainly please describe in the if section
function steamrollArray(arr) {
let answer = [].concat(...arr);
console.log(answer)
if(answer.some(Array.isArray)){
return steamrollArray(answer);
}
return answer
}
let result = steamrollArray([1, [2], [3, [[4]]]]);
// console.log(result)
Have added console.log to help with understanding how the recursion works. Introduced a variable idx to help track the level of recursion.
function steamrollArray(arr, idx=0) {
console.log('bgn--> recursion # ', idx);
console.log('arr: ', JSON.stringify(arr));
let answer = [].concat(...arr);
console.log(
'computed answer: ', JSON.stringify(answer)
);
if(answer.some(Array.isArray)){
// "answer" has an array, so recurse to next level
console.log(
'at least ONE elt in "answer" is an array\n',
'--> making recursive call from recursion #: ',
idx
);
return steamrollArray(answer, idx+1);
};
console.log(
'no elt in "answer" is an array\n',
'no more recursion from recursion #: ', idx,
' answer: ', answer.join(),
' has ZERO arrays ...'
);
return answer;
}
let result = steamrollArray([1, [2], [3, [[4]]]]);
// console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0 }