Skip to content

Instantly share code, notes, and snippets.

@danielmeneses
Last active April 17, 2018 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielmeneses/4d9d73d66083a20e566195a3f6ba0b62 to your computer and use it in GitHub Desktop.
Save danielmeneses/4d9d73d66083a20e566195a3f6ba0b62 to your computer and use it in GitHub Desktop.
Flatten array
const isArray = (obj) => {
return (typeof obj === 'object' && obj.hasOwnProperty('length'));
}
function NotAnArrayException(message) {
this.message = message;
this.name = 'NotAnArrayException';
}
const flattenArray = list => {
if (!isArray(list))
throw new NotAnArrayException('The argument is not an Array!');
const flatten = [];
const recurse = obj => {
if (!isArray(obj)) return;
for (const item of obj) {
if (typeof item === 'number') flatten.push(item);
else recurse(item);
}
};
recurse(list);
return flatten;
};
console.log(flattenArray([[[1]], 2, [[3], {}, true], [10], 22])); // [1, 2, 3, 10, 22]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment