Skip to content

Instantly share code, notes, and snippets.

@sugyan
Forked from handlename/recurse_callback.js
Created October 24, 2011 06:56
Show Gist options
  • Save sugyan/1308517 to your computer and use it in GitHub Desktop.
Save sugyan/1308517 to your computer and use it in GitHub Desktop.
var array = [
1,
2,
[10, 11, 12],
[20, 21, [30, 31]],
3
];
console.log('before');
console.log(array);
flatten(array, function(res) {
console.log('after');
console.log(res);
});
function flatten (array, callback) {
var i, l;
var result = [];
function concat_to_result (a) {
a.forEach(function (e) {
result.push(e);
});
}
for (i = 0, l = array.length; i < l; i++) {
if (array[i] instanceof Array) {
flatten(array[i], concat_to_result);
} else {
result.push(array[i]);
}
}
callback(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment