Created
December 24, 2014 18:15
-
-
Save NickTomlin/13ffd4405fb37b8e526f to your computer and use it in GitHub Desktop.
Recursively flatten an array (e.g. _.flatten but less performant probs)
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
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