Could you please tell me why this code isn't working properly?
The flatten function suppose to remove values from any arrays inside the input array and return those values as a array.
function flatten(arr) {
//create a new array
let newArr = [];
//create a helperFunction
function helperFunction(helperArr) {
//if its an empty array
if (helperArr.length === 0) {
return;
}
//get the first value from the array and remove the value
let firstArrVal = helperArr.shift();
let isAnArray = Array.isArray(firstArrVal);
//if value is an array
if (isAnArray) {
//call recursive function on value
return helperFunction(firstArrVal);
}
//if value isnt an array
else {
//add value to new array
newArr.push(firstArrVal);
//call recursive function on the array
return helperFunction(helperArr);
}
}
//call helperFunction
helperFunction(arr);
//return new array
return newArr;
}
console.log(flatten([1, [2, [3, 4],
[
[5]
]
]]));
// Correct output - [1, 2, 3, 4, 5] - Mine - [1, 2, 3, 4]
For input [1, [2, [3, 4], [[5]]]]
the correct output is [1, 2, 3, 4, 5]
(mine - [1, 2, 3, 4]
)