Skip to content

Instantly share code, notes, and snippets.

@samnajian
Last active July 18, 2016 08:09
Show Gist options
  • Save samnajian/a4cd2e61da4d5b633b7352dcd26a5141 to your computer and use it in GitHub Desktop.
Save samnajian/a4cd2e61da4d5b633b7352dcd26a5141 to your computer and use it in GitHub Desktop.
Flattern array in JS
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