Tell us what’s happening:
Hey can anyone tell me the value of d is infinity and it is passed into the function. I treid to understand at which condition the loop is terminating, but i was unable to grasp the termination condition for the recursive function.
I also copied code in pythin tutuor d value remains infinity on each execution. So what is i am missing here can any one help ?
Your code so far
function steamrollArray(arr) {
// I'm a steamroller, baby
return arr;
}
steamrollArray([1, [2], [3, [[4]]]]);
var arr = [1, 2, [3, 4, [5, 6]]];
// to enable deep level flatten use recursion with reduce and concat
console.log(Array.isArray(arr[2]))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36.
var arr = [1, 2, [3, 4, [5, 6]]];
// to enable deep level flatten use recursion with reduce and concat
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};
flatDeep(arr, Infinity);
Argument d here stands for depth, meaning if you only want to flat array to certain depth of nesting. When Infinity is passed, I suppose it means “flat all levels” Hope this will help
You have 2 ternary operators, first one is in charge of depth-caused exit condition and second one is in charge of base case condition.
The main issue with this code that it’s written in codewars aka one-liner style, that is cool by itself, but messes up readability and production conventions, that tell us: “Base case of recursive function must be the first line in the function body”