I am working on developing my own array flattening method that only goes one level deep. I am using nested loops to iterate through the array and any nested arrays, pushing all elements into a new array. However, I am puzzled as to why there are 'undefined' values in the returned array where the nested array was. Does anyone have any suggestions or insights?
let arr = [1,[2,4],3,2]
function flatten(array) {
let newArr = [];
for (let x = 0; x < array.length; x++){
if (Array.isArray(array[x])){
for (let y = 0; y < array.length; y++){
newArr.push(array[x][y])
}
} else {
newArr.push(array[x])
}
}
return newArr
}
console.log(flatten(arr));
//returns [ 1, 2, 4, undefined, undefined, 3, 2 ]