Skip to content

Instantly share code, notes, and snippets.

@numb86
Created July 11, 2019 04:03
Show Gist options
  • Save numb86/a4f6e0f5a1e2e78d8ffec0c3707e6fab to your computer and use it in GitHub Desktop.
Save numb86/a4f6e0f5a1e2e78d8ffec0c3707e6fab to your computer and use it in GitHub Desktop.
flatten の実装
const target = [1, [2], [3, [4]], [], [[5]]];
function flatten(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
const value = arr[i];
if (typeof value === 'number') {
result.push(value);
continue;
}
for(let x = 0; x < value.length; x++) {
result.push(value[x]);
}
}
const hasArray = result.some(item => Array.isArray(item));
if (hasArray) {
return flatten(result);
};
return result;
}
console.log(flatten(target));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment