Skip to content

Instantly share code, notes, and snippets.

@handlename
Created October 24, 2011 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save handlename/1308489 to your computer and use it in GitHub Desktop.
Save handlename/1308489 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 done = [];
var doneNum = 0;
function check(res) {
done = done.concat(res);
++doneNum;
if (array.length <= doneNum) {
callback(done);
}
}
for (var i = 0; i < array.length; ++i) {
if (array[i] instanceof Array) {
flatten(array[i], function(res) {
check(res);
});
}
else {
check([array[i]]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment