Skip to content

Instantly share code, notes, and snippets.

@jaypeasee
Last active March 5, 2021 19:17
Show Gist options
  • Save jaypeasee/ec59f201c2049efc987253f93b30c597 to your computer and use it in GitHub Desktop.
Save jaypeasee/ec59f201c2049efc987253f93b30c597 to your computer and use it in GitHub Desktop.

Problem - Array Flattener

Rewrite the question in your own words:

Create a function that give the input of an array, it will always return a non nested array. Some inputs may have arrays within arrays. You must do this without any built in methods. I must use recursion to solve the problem as well.

What assumptions will you make about this problem if you cannot ask any more clarifying questions? What are your reasons for making those assumptions?

The inputs can vary on how nested the arrays are.

Some values may be strings, they dont have to all be numbers

I will count objects as arrays.

What are your initial thoughts about this problem? (high level design, 2-3 sentences)

I will need to look into the array and check the type of the element inside of it. Will require loops in addition to recursion.

How would you identify the elements of this problem?

  • Searching of Data
  • Pattern Recognition
  • Optimization

Which data structure(s) do you think you'll use? What pros/cons do you see with that choice?

I will be iterating through the arrays, so arrays are the data structure.

Write out a few lines of initial pseudocode: (mid-level design, NOT REAL CODE)

  • Create a function that takes in an array
  • Create a new variable that will be an upated version cyclically of the param
  • Create a counter for nested arrays
  • iterate through the array to check if any elements are arrays
    • if they are iterate through them and push those values into the update variable and add one to the counter
    • else just push the element into the update variable
  • If the counter is greater than zero, recall the function with the updated variable as the argument
  • else return the updated variable
  • Write out any implementation code OR link to repl

Write out any implementation code OR link to repl

const flattenTheArray = (arrayToEval) => {
  let nestedCount = 0
  const updatedArray = arrayToEval.reduce((updateProgress, element) => {
    if (typeof element === 'object') {
      element.forEach(arrayElement => {
        updateProgress.push(arrayElement)
        nestedCount += 1
      })
    } else {
      updateProgress.push(element)
    }
    return updateProgress
  }, [])
  return nestedCount ? flattenTheArray(updatedArray) : updatedArray
}

flattenTheArray([ 0, 1, 2, [ 3, 4 ], [[4, 5, 6], []] ])

What is the Big O complexity of your solution?

O(n)2 I think because worst case scenario, I have a nested loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment