I want to flat an array, recursion function calls itself till the last element array but not the last element string, I feel like I am missing something important in understanding how recursion works, the string itself is not added to an empty array.
const nested = [[[[[['string']]]]], 5, '7'];
const funcTest = function (arr) {
const final = [];
arr.forEach(el => {
if (Array.isArray(el)) {
console.log(el);
funcTest(el);
} else final.push(el);
});
return final;
};
console.log(funcTest(nested));
You can Flattening all nested arrays With flat taking argument depth of Infinity:
const nested = [[[[[["string"]]]]], 5, "7"];
nested.flat(Infinity); //['string', 5, '7']
depth: The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
You need to add the result of the recursive calls.
const
nested = [[[[[['string']]]]], 5, '7'];
const funcTest = function (arr) {
const final = [];
arr.forEach(el => {
if (Array.isArray(el)) {
console.log(el);
final.push(...funcTest(el)); // <-
} else final.push(el);
});
return final;
};
console.log(funcTest(nested));
Another recursive approach:
const
nested = [[[[[['string']]]]], 5, '7'];
flatValues = item => Array.isArray(item)
? item.flatMap(flatValues)
: item;
console.log(flatValues(nested));
The issue here is that you don't use the return value of the recursive funcTest call.
What you want to do:
const superFlat = (arr) => {
const result = [];
arr.forEach((item) => {
if (!Array.isArray(item)) result.push(item);
else result.push(...superFlat(item));
});
return result;
}
Or just use arr.flat(Infinity)