Skip to content

Instantly share code, notes, and snippets.

@drFabio
Created September 28, 2017 14:20
Show Gist options
  • Save drFabio/e10d28a1e858302535b1c1cb9170d966 to your computer and use it in GitHub Desktop.
Save drFabio/e10d28a1e858302535b1c1cb9170d966 to your computer and use it in GitHub Desktop.
Flatten a nested array into a single level array
const assert = require('assert')
/**
* Returns a nested array into a flatten single level array
* @param {Array} input a multiple level array
* @return {Array} an one level array of all the elements inside
*/
function flatten (input) {
return input.reduce((ret, el) => {
if (Array.isArray(el)) {
ret = ret.concat(flatten(el))
return ret
}
ret.push(el)
return ret
}, [])
}
const expected = [1, 2, 3, 4, 5]
const normal = [1, 2, 3, 4, 5]
assert.deepEqual(expected, flatten(normal))
const oneLevel = [1, 2, 3, 4, [5]]
assert.deepEqual(expected, flatten(oneLevel))
const multipleLEvels = [[[[[[[[1]]]]]]], 2, 3, 4, 5]
assert.deepEqual(expected, flatten(multipleLEvels))
const severalArrays = [[1], [2, 3], [4, 5]]
assert.deepEqual(expected, flatten(severalArrays))
const fullyNested = [[1, 2, 3, 4, 5]]
assert.deepEqual(expected, flatten(fullyNested))
const severalLevels = [[[1], [2, [[3]]], [[[4]], 5]]]
assert.deepEqual(expected, flatten(severalLevels))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment