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.
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.
- Searching of Data
- Pattern Recognition
- Optimization
I will be iterating through the arrays, so arrays are the data structure.
- 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
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], []] ])
O(n)2 I think because worst case scenario, I have a nested loop.