Flatten an Arrray

function flatten(arr){
    let newArr = [];
    console.log(arr)
    if (arr.length === 0) {
        return newArr;
    } 
    if(Array.isArray(arr[0])){
        let conc = newArr.concat(flatten(arr[0]))
        return newArr.concat(conc)
    } else{
        newArr.push(arr[0])
    }
    newArr = newArr.concat(flatten(arr.splice(1)))
    return newArr;
}
  flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5]. 

I am taking the Udemy Course of algorithms and data structures. The goal is to write a function that will flatten an array. For example if the argument passed in is

  flatten([1, [2, [3, 4], [[5]]]])

the function should return

[1, 2, 3, 4, 5]

My function does not seem to account for the deeply nested 5 on the last index of the array. I’m not sure why it doesn’t .

I have been keeping track of what the algorithm is trying to do by using the site below.
http://pythontutor.com/visualize.html#mode=edit

This seems to fall more in line as to what I wanted it to do. However, I still can’t pass the test.

function flatten(arr){
    let newArr = [];
    console.log(arr)
    if (arr.length === 0) {
        return newArr.concat(newArr);
    } 
    if(Array.isArray(arr[0])){
         flatten(arr[0])
    } else{
        newArr.push(arr[0])
    }
    newArr = newArr.concat(flatten(arr.splice(1)))
    return newArr;
}
  flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5].

In this line you aren’t doing anything with value returned by flatten(arr[0]).

the reason it is skipping the 5 is because your only sending arr[0] back into the function so when it becomes this [ [ 3, 4 ], [ [ 5 ] ] ] its only sending [3, 4] back in and [ [ 5 ] ] is lost

1 Like

If it’s any help, freeCodeCamp has this same challenge. It’s called Steamroller. It might be helpful to work on the challenges that lead up to it.

Yes, so the next step was to find how to access one index after another. Here is what i came up with

function flatten(arr){
    let newArr = [];
    console.log(arr)
    if (arr.length === 0) {
        return newArr.concat(newArr);
    } 
    if(Array.isArray(arr[0])){
         newArr = newArr.concat(flatten(arr[0]))
    } else{
        newArr.push(arr[0])
    }
    newArr = newArr.concat(flatten(arr.splice(1)))
    return newArr;
}
  flatten([1, [2, [3, 4], [[5]]]]) // [1, 2, 3, 4, 5]. 

Congratulations on finding a solution! Happy coding.

1 Like

Thank you!. That one was tough.