Created
March 24, 2012 19:04
-
-
Save darraghenright/2186775 to your computer and use it in GitHub Desktop.
Flatten a multidimensional array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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