使用字符串字母顺序的Jquery排序数组

我有一个数组,我想使用名称对象按字母顺序对数组进行排序。


目前,它排序正确,但有一个小问题。


https://jsfiddle.net/b3hv75u8/1/


var arry = [{

    'name': '2.1 Foo',

    'children': [{

        'name': '2.1.1 Foo ',

      },

      {

        'name': '2.1.3 Foo ',

      },

      {

        'name': '2.1.10 Foo ',

      },

      {

        'name': '2.1.2 Foo ',

      },

    ],

  },

  {

    'name': '1.1 Foo',

    'children': [{

        'name': '1.1.2 Foo ',

      },

    ],

  },

];



function SortByName(a, b){

        if(a.children){

            a.children = a.children.sort(SortByName)

        }

        if(b.children){

            b.children = b.children.sort(SortByName)

        }

        var aName = a.name.toLowerCase();

        var bName = b.name.toLowerCase();


        return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));

    }

    

    

    $(document).ready(function() {

      var sorted_array = arry.sort(SortByName)

      console.log(sorted_array)

    })

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


侃侃尔雅
浏览 62回答 1
1回答

开心每一天1111

在比较之前,您需要使用正则表达式来消除点。var arry = [&nbsp; {&nbsp; &nbsp; 'name': '2.1 Foo',&nbsp; &nbsp; 'children': [{&nbsp; &nbsp; &nbsp; &nbsp; 'name': '2.1.1 Foo ',&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'name': '2.1.3 Foo ',&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'name': '2.1.10 Foo ',&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; 'name': '2.1.2 Foo ',&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; ],&nbsp; },&nbsp; {&nbsp; &nbsp; 'name': '1.1 Foo',&nbsp; &nbsp; 'children': [{&nbsp; &nbsp; &nbsp; &nbsp; 'name': '1.1.2 Foo ',&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; ],&nbsp; },];function SortByName(a, b){&nbsp; &nbsp; &nbsp; &nbsp; if(a.children){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a.children = a.children.sort(SortByName)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(b.children){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.children = b.children.sort(SortByName)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var aName = parseInt( a.name.toLowerCase().replace(/\./g, "") );&nbsp; &nbsp; &nbsp; &nbsp; var bName = parseInt( b.name.toLowerCase().replace(/\./g, "") );&nbsp; &nbsp; &nbsp; &nbsp; return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $(document).ready(function() {&nbsp; &nbsp; &nbsp; var sorted_array = arry.sort(SortByName)&nbsp; &nbsp; &nbsp; console.log(sorted_array)&nbsp; &nbsp; })<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript