Skip to content

Instantly share code, notes, and snippets.



Last active Nov 7, 2016
What would you like to do?
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 =
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