Skip to content

Instantly share code, notes, and snippets.

@GeoDoo
Last active June 30, 2017 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeoDoo/cb595728989c7802527b10c6b67e9043 to your computer and use it in GitHub Desktop.
Save GeoDoo/cb595728989c7802527b10c6b67e9043 to your computer and use it in GitHub Desktop.
Flatten multidimensional arrays
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