1

I want to flat an array, recursion function calls itself till the last element array but not the last element string, I feel like I am missing something important in understanding how recursion works, the string itself is not added to an empty array.

const nested = [[[[[['string']]]]], 5, '7'];

const funcTest = function (arr) {
  const final = [];
  arr.forEach(el => {
    if (Array.isArray(el)) {
      console.log(el);
      funcTest(el);
    } else final.push(el);
  });
  return final;
};  

console.log(funcTest(nested));

3
  • please add the wanted result. Commented Nov 17, 2021 at 20:42
  • I want this ['string', 5, '7'] Commented Nov 17, 2021 at 20:43
  • 1
    Did you try .flat? Consider [[[[[['string']]]]], 5, '7'].flat(Infinity) Commented Nov 17, 2021 at 20:45

3 Answers 3

2

You can Flattening all nested arrays With flat taking argument depth of Infinity:

    const nested = [[[[[["string"]]]]], 5, "7"];
    nested.flat(Infinity); //['string', 5, '7']

depth: The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the clarification!
if that is really an answer to the recursive problem, the question would be a duplicate.
It's not the answer, but just I would share a trick to flattening an array without using recursion or for-loops!
Thank you very much
0

You need to add the result of the recursive calls.

const
    nested = [[[[[['string']]]]], 5, '7'];

const funcTest = function (arr) {
  const final = [];
  arr.forEach(el => {
    if (Array.isArray(el)) {
      console.log(el);
      final.push(...funcTest(el)); // <-
    } else final.push(el);
  });
  return final;
};  

console.log(funcTest(nested));

Another recursive approach:

const
    nested = [[[[[['string']]]]], 5, '7'];
    flatValues = item => Array.isArray(item)
        ? item.flatMap(flatValues)
        : item;

console.log(flatValues(nested));

Comments

0

The issue here is that you don't use the return value of the recursive funcTest call.

What you want to do:

const superFlat = (arr) => {
  const result = [];
  
  arr.forEach((item) => {
    if (!Array.isArray(item)) result.push(item);
    else result.push(...superFlat(item));
  });

  return result;
}

Or just use arr.flat(Infinity)

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.