Search code examples
lodash

Lodash sort incorrect with Alphanumberic?


I'm using lodash to sort Array.

Ex:

    const arr = [ { name: 'Card 2' }, { name: 'Card 1' }, { name: 'Card 10' }]

Sort:

    lodash.orderBy(arr, ['name'], ['asc'])

Result:

    [{ name: 'Card 1' }, { name: 'Card 10' }, { name: 'Card 2' }]

How I can resolve it? My expect the result should be:

   [ { name: 'Card 1' }, { name: 'Card 2' }, { name: 'Card 10' }]

Solution

  • It is correct. You are sorting lexicographically. Just like the "aardvark" goes after "a" and before "b", so does "10" go after "1" but before "2". If you want to sort it numerically, you would need to extract the number.

    Here, I split each array into alphabetic and numeric portions, then pad the numeric portions with zeroes so that they can be compared like strings (e.g. "Card 0000000000000010"):

    const arr = [ { name: 'Card 2' }, { name: 'Card 1' }, { name: 'Card 10' }, { name: 'Document 1' }]
    const sortedArr = _.sortBy(arr, [function(o) {
      const split = o.name.split(/\b(\d+)\b/);
      for (let i = 1; i < split.length; i += 2) {
        split[i] = split[i].padStart(16, '0');
      }
      return split.join('');
    }]);
    console.log(sortedArr);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>