一、效果图
1.1 父级
1.2 父级与子级
二、代码
升序降序,只要把 a.num - b.num
改成 b.num - a.num
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
const arr = [
{
name: 1,
num: 3,
children: [
{ name: 11, num: 1, children: [] },
{ name: 12, num: 0, children: [] },
],
},
{
name: 2,
num: 1,
children: [
{ name: 21, num: 3, children: [] },
{ name: 22, num: 1, children: [] },
],
},
{
name: 3,
num: 2,
children: [
{ name: 31, num: 1, children: [] },
{ name: 32, num: 3, children: [] },
],
},
];
console.error(111, arr);
function sortOrderMenu(arr) {
const res = [];
arr
.sort((a, b) => a.num - b.num)
.forEach((val) => {
if (val.children && val.children.length > 0)
val.children = sortOrderMenu(val.children);
res.push(val);
});
return res;
}
const newArr = sortOrderMenu(JSON.parse(JSON.stringify(arr)));
console.error(222, newArr);
</script>
</body>
</html>