[removed] natural sort of alphanumerical strings

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

    The most fully-featured library to handle this as of 2019 seems to be natural-orderby.

    const { orderBy } = require('natural-orderby')
    
    const unordered = [
      '123asd',
      '19asd',
      '12345asd',
      'asd123',
      'asd12'
    ]
    
    const ordered = orderBy(unordered)
    
    // [ '19asd',
    //   '123asd',
    //   '12345asd',
    //   'asd12',
    //   'asd123' ]
    

    It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.

    Surprisingly, it's also only 1.6kB when gzipped.

提交回复
热议问题