Skip to content

Instantly share code, notes, and snippets.

@samnajian samnajian/flatten_array.js
Last active Jul 18, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.