Last active
January 22, 2021 09:11
-
-
Save zhongyangxun/e36148100464edd0a50a2f5fb6b11b6c to your computer and use it in GitHub Desktop.
花式数组扁平化
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 arr = [1, [2, [3], [4]]]; | |
arr.flat(Infinity); | |
function _flat(arr) { | |
return ( | |
Array.isArray(arr) | |
? arr.reduce((acc, cur) => [...acc, ..._flat(cur)], []) | |
: [arr] | |
) | |
} | |
function _flat2(arr) { | |
return ( | |
arr.reduce((acc, curr) => { | |
if(Array.isArray(curr)) { | |
return [...acc, ..._flat2(curr)]; | |
} | |
return [...acc, curr]; | |
}, []) | |
) | |
} | |
function myFlat(arr, depth = 1) { | |
return ( | |
depth > 0 | |
? arr.reduce((acc, curr) => { | |
if(Array.isArray(curr)) { | |
return [...acc, ...myFlat(curr, depth - 1)]; | |
} | |
return [...acc, curr]; | |
}, []) | |
: arr | |
) | |
} | |
function flatWithStack(arr) { | |
const stack = [...arr]; | |
const res = []; | |
while(stack.length) { | |
const curr = stack.pop(); | |
if (Array.isArray(curr)) { | |
stack.push(...curr); | |
} else { | |
res.unshift(curr); | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment