编程语言
首页 > 编程语言> > JavaScript字符串排序(按名称排序)

JavaScript字符串排序(按名称排序)

作者:互联网

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    let arr = [
        {
            name: "移动",
            id: 1,
            children: [
                {
                    name: "联通-004",
                    id: 4,
                    children: [{
                        name: "电信-007",
                        id: 7
                    },
                    {
                        name: "无线网-008",
                        id: 8
                    },
                    {
                        name: "电信-008",
                        id: 9
                    }]
                },
                {
                    name: "123-005",
                    id: 5
                },
                {
                    name: "联通-006",
                    id: 6
                }]
        },
        {
            name: "001通讯",
            id: 2
        },
        {
            name: "003通讯",
            id: 3
        },
        {
            name: "002通讯",
            id: 10
        }
    ]

    function recursion(data) {
        data.map(e => {
            if (e.children) {
                e.children.sort(function (a, b) { return a.name.localeCompare(b.name, 'zh-CN') })
                recursion(e.children)
            }
        })
        return data
    }
    arr.sort(function (a, b) { return a.name.localeCompare(b.name, 'zh-CN') })
    arr = recursion(arr)
    console.log(arr);
</script>

</html>

标签:function,arr,name,recursion,JavaScript,children,字符串,排序,id
来源: https://www.cnblogs.com/LiZiheng/p/16579226.html