Skip to content

Instantly share code, notes, and snippets.

@kevnk
Last active November 7, 2016 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevnk/dd85586cda370bbb52e5aa40129cef4c to your computer and use it in GitHub Desktop.
Save kevnk/dd85586cda370bbb52e5aa40129cef4c to your computer and use it in GitHub Desktop.
Flatten Array
/**
* Takes a nested array and flattens it. Default use is for a nested array of integers
* But can be used for nested arrays with any type of value by passing in custom mapping and/or filtering functions
* @param {Array} arr The nested array to be flattened
* @param {Function} mapIt Function to map each value
* @param {Function} filterIt Function to filter out unwanted values left over from the mapping
* @return {Array} Returns empty array if `arr` is invalid
*/
export default function flatten(arr, mapIt=Number, filterIt=Number.isInteger) {
let result = []
if (Array.isArray(arr) && arr.length) {
result = arr.join().split(',')
if (typeof mapIt === 'function') result = result.map(mapIt)
if (typeof filterIt === 'function') result = result.filter(filterIt)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment