Skip to content

Instantly share code, notes, and snippets.

@juanmaguitar
Created December 9, 2019 10:20
Show Gist options
  • Save juanmaguitar/edc123fb29fc7bae21737186c386e125 to your computer and use it in GitHub Desktop.
Save juanmaguitar/edc123fb29fc7bae21737186c386e125 to your computer and use it in GitHub Desktop.
const assert = require('assert');
/**
* flattenArray
* Flatten an array of arbitrarily nested arrays of integers
* into a flat array of integers
* e.g. [[1,2,[3]],4] -> [1,2,3,4].
*
* @param {array} arrayNested Array to be flattened
*
* @return{result} returns the flattened array
*/
const flattenArray = arrayToBeFlattened =>
arrayToBeFlattened.reduce((accFlattened, item) =>
accFlattened.concat(Array.isArray(item) ? flattenArray(item) : item)
,[]
)
/* ------------- TESTS ------------- */
assert(typeof flattenArray !== 'undefined', 'flattenArray should exist')
assert(typeof flattenArray == 'function', 'flattenArray should be a function')
assert((() => {
const CASE1 = [[1,2,[3]],4]
const CASE2 = [1,2,3,4]
const CASE3 = [[[[[[1,2,3,4]]]]]]
const EXPECTED_RESULT = JSON.stringify([ 1, 2, 3, 4 ])
return [CASE1, CASE2, CASE3]
.map(flattenArray)
.map(JSON.stringify)
.every(resultCase => resultCase === EXPECTED_RESULT)
})(), 'flattenArray should flatten an arbitrarily nested arrays of integers')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment