Last active
July 18, 2016 08:09
-
-
Save samnajian/a4cd2e61da4d5b633b7352dcd26a5141 to your computer and use it in GitHub Desktop.
Flattern 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
function flatten_array( arr ){ | |
/** | |
* Checks if _arr is an array | |
* @param Array|Mixed _arr variable to check | |
* @return Bool whether _arr is an array | |
*/ | |
const is_array = ( _arr ) => { | |
return typeof _arr === "object" && typeof _arr.concat === "function"; | |
}; | |
/** | |
* Return an error object if arr is not an Array | |
*/ | |
if( !is_array( arr ) ){ | |
return new Error("Invalid argument provided " , arr , " should be an array" ); | |
} | |
/** | |
* Reduces nested arrays into flattened array recursively | |
* | |
* @param Array res result of previous loop | |
* @param Array|Number item current item | |
* @return Array Reduced array | |
*/ | |
const _reducer = (res, item) => { | |
if( is_array( item ) ) | |
return res.concat( item.reduce( _reducer, [] ) ); | |
else | |
res.push(item); | |
return res ; | |
}; | |
/** | |
* Reduce arr to flattened array | |
*/ | |
return arr.reduce( _reducer, [] ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment