Last active
June 30, 2017 13:27
-
-
Save GeoDoo/cb595728989c7802527b10c6b67e9043 to your computer and use it in GitHub Desktop.
Flatten multidimensional arrays
This file contains hidden or 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
function flatten(arr) { | |
return arr.reduce(function (flat, toFlatten) { | |
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); | |
}, []); | |
} | |
function assertFlattenEquals(actual, expected, testName) { | |
if (JSON.stringify(actual) === JSON.stringify(expected)) { | |
console.log('\'' + testName + '\' test passed!'); | |
} else { | |
console.log('FAILED: ' + testName + ', ' + actual + ' expected to be ' + expected); | |
} | |
} | |
var actual = flatten([[1,2,[3]],4]); | |
var expected = [1, 2, 3, 4]; | |
assertFlattenEquals(actual, expected, 'The array flattens correctly'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment