Recursive function problems in javascript

Asked 1 years ago, Updated 1 years ago, 419 views

function flatten(oldArr) {
  var newArr = []
  for (var i = 0; i < oldArr.length; i++) {
    if (Array.isArray(oldArr[i])) {
      newArr = newArr.concat(flatten(oldArr[i]))
    } } else {
      newArr.push(oldArr[i])
    }
  }
  return newArr;
}

// // flatten([[1],[2],[3]]) // [1,2,3]
// // flatten([[[[1], [[[2]]], [[[[[[[3]]]]]]]]]]) // [1,2,3]

The problem is to use a recursive function to have only one output of all the values in the array. I couldn't solve it, so I saw the answer. I don't know the logic of operation in the code for statement. What will be the logic of the code's operation?

javascript recursive flatten

2023-01-20 14:49

1 Answers

One thing to have in dealing with recursive functions is belief in functions. Here, the flatten function is a function that makes the array flat. When implementing the content of the function, let's believe that the flatten function that appears in the code in the function is correct.

You might be confused about what I'm saying. Let me give you an example.

const arr = [
  [1, [2, 3, 4], [5, [6], 7]],
  [3, 1, 4, [1]],
  5, 9,
  [2, 6, 5]
]

Suppose we want to do arr for flatten.

So let's believe that this flatten function is implemented and think about what happens when we turn the for-loop above for each element of arr.

  [1, [2, 3, 4], [5, [6], 7]],
  // // flatten 후 -> [1, 2, 3, 4, 5, 6, 7]
  [3, 1, 4, [1]],
  // // flatten 후 -> [3, 1, 4, 1]
  5,
  // -> Not an array, so stay.
  9,
  // -> Not an array, so stay.
  [2, 6, 5]
  // // flatten 후 -> [2, 6, 5]

in the end

newArr = newArr.concat([1, 2, 3, 4, 5, 6, 7])
newArr = newArr.concat([3, 1, 4, 1])
newArr.push(5)
newArr.push(9)
newArr = newArr.concat([2, 6, 5])

You can see that it's going to be the [1, 2, 3, 4, 5, 6, 7, 3, 1, 4, 1, 5, 9, 2, 6, 5] . I believed that flatten written in the function would run well, and I can see that the results are working.

It is in line with analyzing recursive functions. If you have to write a recursive function called flatten from scratch, suppose you already have the correct flatten function and think about how to use it, it's a little easier to squeeze. It would be better if the direction of thinking was "to split a big problem into small problems" (otherwise, I could create a code like function platten(oldArr) { return platten(oldArr)}).)

Let's look at the situation in arr mentioned earlier. Let's do arr to flatten.


2023-01-20 19:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.