Last active
April 17, 2018 20:20
-
-
Save danielmeneses/4d9d73d66083a20e566195a3f6ba0b62 to your computer and use it in GitHub Desktop.
Flatten array
This file contains 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
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