Skip to content

Instantly share code, notes, and snippets.

@guzmonne
Created July 10, 2017 11:45
Show Gist options
  • Select an option

  • Save guzmonne/51bcebb7837f92fbc9a6486aa42685cf to your computer and use it in GitHub Desktop.

Select an option

Save guzmonne/51bcebb7837f92fbc9a6486aa42685cf to your computer and use it in GitHub Desktop.
Arbitrary flattens a nested array.
/**
* Flattens an array of arbitrarily nested arrays into a flat array.
* E.g. [[1,2,[3]],4] -> [1,2,3,4].
* @param {array} array Array to be flatten.
*/
function flatten(array) {
/**
* Checks if the given array has any nested array.
* @param {array} array Array to check if it is flat.
*/
const isFlat = (array) => array.every(x => Array.isArray(x) === false)
array = array.reduce((acc, x) => acc.concat(x), [])
return isFlat(array) ? array : flatten(array)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment