I've been working on creating a simple function in ES5 to deep flatten an array. The current implementation appears to work, but it seems suboptimal because the res
results array is defined outside of the actual flatten function.
var arr = [1, 2, [3], [4, [5, [6, 7, 8, 9, 10, 11]]]]
, res = [];
function flatten(item){
if (Array.isArray(item)) {
item.forEach(el => {
return flatten(el, res);
});
}else {
res.push(item);
}
}
flatten(arr);
console.log(res); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Trying something similar with an IIFE seems promising:
function flatten(item){
var res = [];
return (function(ress){
if (Array.isArray(item)) {
item.forEach(el => {
return flatten(el);
});
}else {
res.push(item);
}
})(res);
}
However, I have not quite achieved the desired outcome as res
remains undefined here. Ideally, the final line of the function should return res
so that the function can be utilized like var f = flatten(arr)
.
NB
*This question does not focus solely on how to deep flatten an array, as there are numerous solutions available for that. My main interest lies in finding a way to keep the results variable inside the parent function in this particular case. *