I am trying to solve this problem with recursion because I want to make my life worse. I am taking an array of arrays and returning one array with all of the values. It is so close to working but the new array I am pushing to keeps reseting after every recursion. Can I get some advice?
var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]
const flatten = function (arr) {
let output = [];
arr.map(element => {
if (Array.isArray(element)) {
console.log('Is Array ---> ', element)
flatten(element);
} else {
console.log('Output ----->', output)
console.log('Else --->', element)
output.push(element);
}
});
return output;
};
console.log('Retrun ----->', flatten(myArray)); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
map, you callflattenbut you never use the result. Also, using amapbut not using its return value can be misleading.forEachmay be more appropriate