Last active
March 17, 2022 06:13
-
-
Save zzzgydi/93c4e5603503f5eda2d8e27daa8289c5 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 test = [ | |
"./home/analysis", | |
"./home/boardTodo", | |
"./home/dairy", | |
"./home", | |
"./home/todo", | |
"./index", | |
"./profile" | |
]; | |
function solve(array) { | |
const map = {}; | |
array.forEach((each) => save(each)); | |
return map['.']?.children; | |
function save(path) { | |
let current = map[path]; | |
if (!current) { | |
current = { path: path.slice(1) }; | |
map[path] = current; | |
} | |
const pathList = path.split('/'); | |
pathList.pop(); | |
if (pathList.length) { | |
const parent = save(pathList.join('/')); | |
if (!parent.children?.length) { | |
parent.children = []; | |
} | |
if (!parent.children.includes(current)) { | |
parent.children.push(current); | |
} | |
} | |
return current; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment