Created
September 28, 2017 14:20
-
-
Save drFabio/e10d28a1e858302535b1c1cb9170d966 to your computer and use it in GitHub Desktop.
Flatten a nested array into a single level 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
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