Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Last active January 22, 2021 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongyangxun/e36148100464edd0a50a2f5fb6b11b6c to your computer and use it in GitHub Desktop.
Save zhongyangxun/e36148100464edd0a50a2f5fb6b11b6c to your computer and use it in GitHub Desktop.
花式数组扁平化
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