Created
July 11, 2019 04:03
-
-
Save numb86/a4f6e0f5a1e2e78d8ffec0c3707e6fab to your computer and use it in GitHub Desktop.
flatten の実装
This file contains hidden or 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 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