Skip to content

Instantly share code, notes, and snippets.

@darraghenright
Created March 24, 2012 19:04
Show Gist options
  • Save darraghenright/2186775 to your computer and use it in GitHub Desktop.
Save darraghenright/2186775 to your computer and use it in GitHub Desktop.
Flatten a multidimensional array
/**
* Flatten array
*
* Iterate over array elements.
* Recurse into sub arrays.
*/
function flatten(a, f) {
var f = f || []; // init result array
a.forEach(function(e) {
(e.push && e.slice && e.join) ? flatten(e, f) : f.push(e);
});
return f; // done :)
}
// array of random values
var a = [{ one: 1 }, 2, 3, 4, ['five', 6, [7, 8, [9, 10, ['eleven']]]], 12, [], 'thirteen'];
console.log(flatten(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment