[removed] natural sort of alphanumerical strings

后端 未结 7 1482
抹茶落季
抹茶落季 2020-11-21 10:19

I\'m looking for the easiest way to sort an array that consists of numbers and text, and a combination of these.

E.g.

\'123asd\'
\'19asd\'
\'12345asd\'         


        
7条回答
  •  不知归路
    2020-11-21 10:36

    If you have a array of objects you can do like this:

    myArrayObjects = myArrayObjects.sort(function(a, b) {
      return a.name.localeCompare(b.name, undefined, {
        numeric: true,
        sensitivity: 'base'
      });
    });
    

    var myArrayObjects = [{
        "id": 1,
        "name": "1 example"
      },
      {
        "id": 2,
        "name": "100 example"
      },
      {
        "id": 3,
        "name": "12 example"
      },
      {
        "id": 4,
        "name": "5 example"
      },
    
    ]
    
    myArrayObjects = myArrayObjects.sort(function(a, b) {
      return a.name.localeCompare(b.name, undefined, {
        numeric: true,
        sensitivity: 'base'
      });
    });
    console.log(myArrayObjects);

提交回复
热议问题