Created
July 8, 2016 00:45
-
-
Save craveytrain/a0000a2db74a500742a950db6dc2e44a to your computer and use it in GitHub Desktop.
flatten array in js
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
/** | |
* 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