I want to write a function that can deep flatten a given array. For example:
deepFlatten([]); // []
deepFlatten([1, 2, 3]); // [1, 2, 3]
deepFlatten([[1, 2, 3], ["a", "b", "c"], [1, 2, 3]]); // [1, 2, 3, "a", "b", "c", 1, 2, 3]
deepFlatten([[3], [4], [5]], [9], [9], [8], [[1, 2, 3]]]); // [3, 4, 5, 9, 9, 8, 1, 2, 3]
I try to solve this recursively and so far I've got this:
var deepFlatten = function (array){
var result = [];
array.forEach(function (elem) {
if (Array.isArray(elem)) {
result.concat(deepFlatten(elem)); // problem probably lies here
} else {
result.push(elem);
}
});
return result;
};
This however only pushes non-array elements to result and completely ignores the concatenating part. How can I fix this or is there a better way to write this function without the help of any external library?