Created
January 3, 2019 02:52
-
-
Save nicwestvold/c5576626b76db740a3ba0c7c44625e27 to your computer and use it in GitHub Desktop.
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
// `flatten` will flatten an array of arbitrarily nested arrays of integers | |
// into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4] | |
var flatten = (arr) => { | |
// if arr isn't an array, just return an empty array... for now | |
// there should be better rules around this | |
if (!arr || !Array.isArray(arr)) []; | |
var result = arr.reduce((acc, curr) => { | |
// if the current value (curr) is an array, we need to | |
// recursively call `flatten` | |
if (Array.isArray(curr)) { | |
return acc.concat(flatten(curr)); | |
} else { | |
return acc.concat([curr]); | |
} | |
}, []); | |
// filter out any non-number values | |
return result.filter((el) => typeof el === 'number'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment