Skip to content

Instantly share code, notes, and snippets.

@ibigbug
Last active August 29, 2015 14:05
Show Gist options
  • Save ibigbug/d947e5e240ccd4820d02 to your computer and use it in GitHub Desktop.
Save ibigbug/d947e5e240ccd4820d02 to your computer and use it in GitHub Desktop.
Flatten Array
function flatten(input) {
'use strict';
if (!Array.isArray(input)) // need polyfill
return input;
var ret = [];
(function inner(input, ret) {
if (input.length === 0)
return ret;
var car = input.shift(0);
if (!Array.isArray(car)) {
ret.push(car);
} else {
inner(car, ret);
}
inner(input, ret);
})(input, ret);
return ret;
}
console.log(flatten([1, [2, 3, [4, 5], [6, 7]], [8, 9], 10]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment