[removed] natural sort of alphanumerical strings

后端 未结 7 1470
抹茶落季
抹茶落季 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:55

    This is now possible in modern browsers using localeCompare. By passing the numeric: true option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'. Tested in Chrome, Firefox, and IE11.

    Here's an example. It returns 1, meaning 10 goes after 2:

    '10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})

    For performance when sorting large numbers of strings, the article says:

    When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link

    var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
    var myArray = ['1_Document', '11_Document', '2_Document'];
    console.log(myArray.sort(collator.compare));

    0 讨论(0)
提交回复
热议问题