Skip to content

Instantly share code, notes, and snippets.

@fanaugen
Created January 12, 2016 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanaugen/4f6f5f1871c0ad160db3 to your computer and use it in GitHub Desktop.
Save fanaugen/4f6f5f1871c0ad160db3 to your computer and use it in GitHub Desktop.
recursive function to flatten a js Array
function steamroller(arr) {
for (var i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
// recurse: replace this array with all its elements
// for instance, if arr is [1, [2, 3], 4]
// then we want to return [1, 2, 3, 4]
var left = arr.slice(0, i);
var right = arr.slice(i + 1);
return steamroller(
left.concat( arr[i] ).concat(right)
);
}
}
// base case: we haven’t returned until this point, which
// means that none of the elements of arr are arrays, so
// arr is flat.
return arr;
}
@fanaugen
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment