Created
October 15, 2019 00:31
-
-
Save zachlysobey/0d9c3a12d2afc23354c66c46909f360e to your computer and use it in GitHub Desktop.
JS function to flatten an arbitrarily nested array
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
// creates a new array with all sub-array elements concatenated into it recursively | |
// equivalent to array.prototype.flat with Infinity passed for depth | |
const flattenArray = (arr) => | |
arr.reduce( | |
(result, value) => result.concat( | |
Array.isArray(value) | |
? flattenArray(value) | |
: value | |
), | |
[], | |
) | |
// TESTS | |
const assert = require('assert') | |
const testCases = [ | |
[1, [2, 3, [4], 5]], | |
[1, 2, 4], | |
[], | |
[1], | |
[[[[[[7]]]]]], | |
] | |
testCases.forEach(arr => { | |
const actual = flattenArray(arr) | |
const expected = arr.flat(Infinity) | |
assert.deepEqual( | |
expected, | |
actual, | |
` | |
expected: ${JSON.stringify(expected)} | |
actual: ${JSON.stringify(actual)} | |
` | |
) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment