Skip to content Skip to sidebar Skip to footer

I Am Trying To Flatten The Array Regardless Of The Level. I Run It In Debugger.it Is Working Well Until The Last Curly Bracket

At last step function would return med=[1].But return d take my code to the beginning and change all the values.

Solution 1:

User "vleonc" has already explained the problems with your attempt. Here's some other ways to solve the problem:

This function reduces an array into a new array, at each step concatenating either the value or the result of a recursive call on the value, depending on whether the value is an array:

constflatten1 = (xs) =>
  xs .reduce (
    (a, x) => a .concat (Array .isArray (x) ? flatten1 (x) : x), 
    []
  )

But flatMap can simplify this for us, removing the need for reduce and concat. This is clearly simpler:

constflatten2 = (xs) => 
  xs .flatMap (x =>Array .isArray (x) ? flatten2 (x) : x)

But we're not done. It turns out that this is already built in! The array method flat does exactly this job. It accepts an integer parameter and flattens arrays up to that depth. If we use the parameter Infinity it flattens out any nested arrays. So we come to this:

constflatten3 = (xs) =>
  xs .flat (Infinity)

And of course this is now simple enough that we can choose to inline it instead of use a function at all:

const result = arr.flat (Infinity)

I probably wouldn't do this myself. I prefer working with functions. But we should note that it's simple enough, and we may not want to bother with a function if it's only used once.

You can see all these in action in the following snippet:

constflatten1 = (xs) =>
  xs .reduce (
    (a, x) => a .concat (Array .isArray (x) ? flatten1 (x) : x), 
    []
  )

constflatten2 = (xs) => 
  xs .flatMap (x =>Array .isArray (x) ? flatten2 (x) : x)

constflatten3 = (xs) =>
  xs .flat (Infinity)

const arr = [[[[8], 6, 7]], [5, [3]], 0, [[[[9]]]]]

console .log (flatten1 (arr))
console .log (flatten2 (arr))
console .log (flatten3 (arr))
console .log (arr .flat (Infinity))
.as-console-wrapper {max-height: 100%!important; top: 0}

Solution 2:

The main problem here is that each time the function is called again inside itself, it initialises d as an empty array, as it is the first line, so the value you had previously is lost.

In order to avoid this, you have some options:

  • one would be to keep const d = [] outside your function and you don't return anything. Each time you call your function, the results will be pushed inside.

  • the other option is to keep the value as a second argument to the function for recursive calls, like i did in my answer for flatten(arg). For your first call it will be null by default. Otherwise, if it is truthy, it will use the value in order to be saved in d.

Note that I do use d as second argument in the recursive call in this second option

EDIT: I've added the function flattenWithOneArg(arg), which demonstrates the first option I commented above. As you can see, the const d is declared outside the function, and the function doesn't return any value. It just pushes the results inside my outside variable

const d = [];
functionflattenWithOneArg(arg) {
    if (!Array.isArray(arg)) {
        d.push(arg);
    } else {
        flatten(arg.reduce((a, b) => a.concat(b)), d);
    }
}

functionflatten(arg, result = null) {
    const d = !!result ? result : []
    if (!Array.isArray(arg)) {
        d.push(arg);
    } else {
        flatten(arg.reduce((a, b) => a.concat(b)), d);
    }
    return d;
}


console.log(flatten([[[[[['foo']]], [[[[['bar']]]]]]]]));
console.log(flatten([[[1]]]));

flattenWithOneArg([[[[[[1]]]]]]);
console.log(d);

Post a Comment for "I Am Trying To Flatten The Array Regardless Of The Level. I Run It In Debugger.it Is Working Well Until The Last Curly Bracket"