首页 > 解决方案 > 使用字符串字母顺序的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>

对于上面的代码输出是

 [
  {
    "name": "1.1 Foo",
    "children": [
      {
        "name": "1.1.2 Foo "
      }
    ]
  },
  {
    "name": "2.1 Foo",
    "children": [
      {
        "name": "2.1.1 Foo "
      },
      {
        "name": "2.1.10 Foo "    // this is wrong
      },
      {
        "name": "2.1.2 Foo "
      },
      {
        "name": "2.1.3 Foo "
      }
    ]
  }
]

预期操作

[
  {
    "name": "1.1 Foo",
    "children": [
      {
        "name": "1.1.2 Foo "
      }
    ]
  },
  {
    "name": "2.1 Foo",
    "children": [
      {
        "name": "2.1.1 Foo "
      },
      {
        "name": "2.1.2 Foo "
      },
      {
        "name": "2.1.3 Foo "
      },
      {
        "name": "2.1.10 Foo "
      }
    ]
  }
]

标签: javascriptjquery

解决方案


在比较之前,您需要使用正则表达式来消除点。

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 = parseInt( a.name.toLowerCase().replace(/\./g, "") );
        var bName = parseInt( b.name.toLowerCase().replace(/\./g, "") );

        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>


推荐阅读