js数组实现简单排序

    <script>
        var json = [
            {
                "name": "张三",
                "course": "数学",
                "grade": 100
            },
            {
                "name": "张三",
                "course": "语文",
                "grade": 99
            },
            {
                "name": "李四",
                "course": "外语",
                "grade": 88
            },
            {
                "name": "张三",
                "course": "外语",
                "grade": 98
            },
            {
                "name": "李四",
                "course": "语文",
                "grade": 90
            },
            {
                "name": "李四",
                "course": "数学",
                "grade": 89
            },
            {
                "name": "张思",
                "course": "外语",
                "grade": 98
            },
            {
                "name": "张思",
                "course": "语文",
                "grade": 90
            },
            {
                "name": "张思",
                "course": "数学",
                "grade": 89
            }
        ]
        
    json= json.sort((student1, student2) => {
        
        //console.log(student2.name - student1.name);
        //console.log(student2.grade + "----" + student1.grade);
        //console.log(student2.name - student1.name);
        
        //var result = (student2.name + student2.course + student2.grade) > (student1.name + student1.course + student1.grade) ? 1 : -1;
        //var result = (student2.name + student2.course + student2.grade) > (student1.name + student1.course + student1.grade) ? 1 : -1;
        
        var result = (student1.name + student1.course + student1.grade).localeCompare((student2.name + student2.course + student2.grade), 'zh-CN');
        
        return result;
    });  
    console.log(json);
        
    </script>

以上代码按找姓名、课程升序排序。

主要是利用: arr.sort 和 item1.localeCompare(item2, 'zh-CN'); 

posted @ 2021-06-02 10:27  屌丝大叔的笔记  阅读(95)  评论(0编辑  收藏  举报