Skip to content

Instantly share code, notes, and snippets.

@nicwestvold
Created January 3, 2019 02:52
Show Gist options
  • Save nicwestvold/c5576626b76db740a3ba0c7c44625e27 to your computer and use it in GitHub Desktop.
Save nicwestvold/c5576626b76db740a3ba0c7c44625e27 to your computer and use it in GitHub Desktop.
// `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