Skip to content

Instantly share code, notes, and snippets.

@davidchase
Created February 13, 2017 01:03
Show Gist options
  • Save davidchase/cf30b6a10b50061d177a9b07b6fa6368 to your computer and use it in GitHub Desktop.
Save davidchase/cf30b6a10b50061d177a9b07b6fa6368 to your computer and use it in GitHub Desktop.
// Array#reduce + recursion to flatten
// any level of nested arrays
// So we reduce the nested array and aggregate the values of the Integer type into the seed array
// during the aggregation we 1st check if the values from the input array are of the Array type via `isArray`
// if so we call the function `flatten` again passing that array value as input and if the value is
// not of the Array type it we `concat` the value with the seed array
// below is a timeline of how the values look after the input array is given
// [[1, 2, [3]], 4]: --- [1,2,[3]] --> 1 --> 2 --> [3] --> 3 --> 4
const flatten = array => array.reduce((acc, val) => acc.concat(Array.isArray(x) ? flatten(val) : val), [])
const list = [[1, 2, [3]], 4]
const list1 = [[[1]], 2, [3], [4], [[[5]]]]
// using Node.js Assert
assert.deepStrictEqual([1, 2, 3, 4], flatten(list))
assert.deepStrictEqual([1, 2, 3, 4, 5], flatten(list1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment