Created
August 9, 2017 15:40
-
-
Save mikeapr4/de489a4a56313c474a27447336ebfcd9 to your computer and use it in GitHub Desktop.
Flatten Nested Arrays in Javascript
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
// See this in action: https://jsfiddle.net/mikeapr4/t4x0oe9k/ | |
// Queue-orientated solution, will work for large-scale | |
// nesting (50k+), however additional overhead of space (queue) | |
const flatten = A => { | |
const output = [], queue = [...A] | |
while (queue.length > 0) { | |
const entry = queue.shift() | |
if (Array.isArray(entry)) { | |
queue.unshift(...entry) | |
} | |
else { | |
output.push(entry) | |
} | |
} | |
return output | |
} | |
// Simpler solution more likely for general use, faster and | |
// less memory without queue. | |
const flattenRecurse = A => A.reduce((output,entry) => { | |
if (Array.isArray(entry)) { | |
output.push(...flattenRecurse(entry)) | |
} | |
else { | |
output.push(entry) | |
} | |
return output | |
}, []) | |
const tests = [ | |
{inp: [[1,2,[3]],4], outp: [1,2,3,4]}, | |
{inp: [[1,2,[]],4], outp: [1,2,4]}, | |
{inp: [1,2,3], outp: [1,2,3]}, | |
{inp: [], outp: []} | |
] | |
const pass = tests.every(t => _.isEqual(flatten(t.inp), t.outp)) | |
$('#result').append(pass ? 'all flatten passed\n' : 'some flatten failed\n'); | |
const passRec = tests.every(t => _.isEqual(flattenRecurse(t.inp), t.outp)) | |
$('#result').append(passRec ? 'all flattenRecurse passed' : 'some flattenRecurse failed'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment