Last active
November 7, 2016 18:54
-
-
Save kevnk/dd85586cda370bbb52e5aa40129cef4c to your computer and use it in GitHub Desktop.
Flatten Array
This file contains hidden or 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
/** | |
* 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