How recursive function is working to flatten array

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

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.

Challenge: Steamroller

Link to the challenge:

what are you talking about? there is nothing like that in the code you posted

can you post or link the code you are talking about

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);

Sorry i got the right code now

Hey anyone help me pls

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” :wink: Hope this will help

Yes i know it means to flat all levels, but here i have used recursive function, how function exit?. I mean what is the returning condition here

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” :slight_smile:

1 Like

this is not an instant messaging board, you don’t need to ping people like that, someone will answer you, with a bit of patience

1 Like

Ohh, Thanks. But what i was asking was how this whole recursive function is ending,since the depth always gonna be infinity.

look at the ternary

Array.isArray(val) ? flatDeep(val, d - 1) : val

do you understand how a ternary operator works?
in one case happen recursion, in the other (stopping condition) it doesn’t

Yes i understand. I got it, now thanks.