Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Created October 15, 2019 00:31
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 zachlysobey/0d9c3a12d2afc23354c66c46909f360e to your computer and use it in GitHub Desktop.
Save zachlysobey/0d9c3a12d2afc23354c66c46909f360e to your computer and use it in GitHub Desktop.
JS function to flatten an arbitrarily nested array
// 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