Skip to content

Instantly share code, notes, and snippets.

@d-oliveros
Created July 25, 2016 23:03
Show Gist options
  • Save d-oliveros/96a2fded89277758fa3f8f0ddf9b1d75 to your computer and use it in GitHub Desktop.
Save d-oliveros/96a2fded89277758fa3f8f0ddf9b1d75 to your computer and use it in GitHub Desktop.
/**
* Recursively flattens an array.
*
* @param {Array} arr Array to flatten.
* @return {Array} Flattened array.
*/
function flatten(arr) {
var flattened = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (Array.isArray(arr[i])) {
flattened.push.apply(flattened, flatten(arr[i]));
} else {
flattened.push(arr[i]);
}
}
return flattened;
}
console.log(flatten([[1,2,[3]],4])); // [1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment