Skip to content

Instantly share code, notes, and snippets.

@manduks
Created March 5, 2019 00:30
Show Gist options
  • Save manduks/28e30f09dc11760d31e819917a258fa0 to your computer and use it in GitHub Desktop.
Save manduks/28e30f09dc11760d31e819917a258fa0 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
/**
* 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].
**/
const isInteger = (n) => {
if(Number.isInteger(n)) {
return n;
};
throw "An item inside the array is not integer";
}
let flatten = list => {
if (!Array.isArray(list)) {
throw "Not an array";
}
return list.reduce(
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : isInteger(b)), []
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment