Skip to content
Advertisement

flatten an array recursively

I tried to implement an array flatten function recursively. Here is the code:

JavaScript

But I don’t know why the result is not correct. Please help me explain it.

Advertisement

Answer

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

flatArr.concat(...) doesn’t change flatArr… you need to assign it like so:

flatArr = flatArr.concat('flatten(arr[i]));

Here is a working example with 3 levels deep array:

JavaScript
JavaScript

You can read more about Array.concat function here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement