My recommendation would be to take a dependency on lodash and use the flattenDeep
function.
_.flattenDeep([1,2,[2,3],[5,[6,1],4],7])
// [ 1, 2, 2, 3, 5, 6, 1, 4, 7 ]
If you want to write your own function, you might want to peek at the lodash implementation.
In pseudo-code, here's a recursive approach:
result = []
function flatten(array)
for each element in array
if element is array
flatten(element)
else
result.append(element)
EDIT
Here's a "by-hand" approach, though I'd definitely recommend relying on the better-tested lodash implementation.
function flatten(arr, result) {
if (result === undefined) {
result = [];
}
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatten(arr[i], result);
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(flatten([1, 2, [2, 3], [5, [6, 1], 4], 7]));
// Output:
// [ 1, 2, 2, 3, 5, 6, 1, 4, 7 ]