Skip to content

Instantly share code, notes, and snippets.

@HuangXiZhou
Created April 22, 2018 04:05
Show Gist options
  • Save HuangXiZhou/3a26ec56ee1f1b6d2690f2ec37c607f4 to your computer and use it in GitHub Desktop.
Save HuangXiZhou/3a26ec56ee1f1b6d2690f2ec37c607f4 to your computer and use it in GitHub Desktop.
JavaScript Arrary flat functions
// Use recursion
function flatten(arr) {
let result = [];
arr.forEach(el => {
if (el instanceof Array) {
result = result.concat(flatten(el));
} else {
result.push(el);
}
});
return result;
}
// Without use recursion
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment