Skip to content

Instantly share code, notes, and snippets.

@craveytrain
Created July 8, 2016 00:45
Show Gist options
  • Save craveytrain/a0000a2db74a500742a950db6dc2e44a to your computer and use it in GitHub Desktop.
Save craveytrain/a0000a2db74a500742a950db6dc2e44a to your computer and use it in GitHub Desktop.
flatten array in js
/**
* Flattens nested arrays
*
* @param {array} arr - The nested array
* @returns {array} Returns flattened array
*
* @example
* // returns [ 1, 2, 3, 4 ]
* flattenArray( [ [ 1, 2, [ 3 ] ], 4 ] );
*
* checks if param is array
* if so, runs concat on expanded members of map of array, recusrively calling function until it no longer hits an array
* if not, returns the non-array param
*/
const flattenArray = arr => Array.isArray( arr ) ? [].concat( ...arr.map( flattenArray ) ) : arr;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment