Skip to content

Instantly share code, notes, and snippets.

@NickTomlin
Created December 24, 2014 18:15
Show Gist options
  • Save NickTomlin/13ffd4405fb37b8e526f to your computer and use it in GitHub Desktop.
Save NickTomlin/13ffd4405fb37b8e526f to your computer and use it in GitHub Desktop.
Recursively flatten an array (e.g. _.flatten but less performant probs)
var assert = require('assert');
function reflatten (source, accum) {
accum = accum || [];
if (Array.isArray(source)) {
source.forEach(function (child) {
if (Array.isArray(child)) {
reflatten(child, accum);
} else {
accum.push(child);
}
});
}
return accum;
}
var before = [[1,2,3], 4, [5,6 ,7, [8, 9], [10, [11, 12]]]];
var result = reflatten(before);
assert.deepEqual(result, [1,2,3,4,5,6,7,8,9,10,11,12]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment