Search code examples
javascriptlodash

How to use Lodash orderby with a custom function?


I am using Lodash's orderby to sort a number of elements based on a key property.

I want to prioritize them by another property (capacity) which is number from 0 to 9. Items with 0 capacity should be sorted at the end and all other items should be sorted by the key.

So capacity property should be converted to a boolean value. I want to do this without changing the original object or adding a new property or making a new array.

Sample data:

    [
      {
        "priceChild": 4098000,
        "priceAdult": 4098000,
        "priceInfant": 998000,
        "displayIndex": 4,
        "capacity": 5
      },
      {
        "priceChild": 3698000,
        "priceAdult": 3698000,
        "priceInfant": 898000,
        "displayIndex": 5,
        "capacity": 1
      },
      {
        "priceChild": 3006000,
        "priceAdult": 3980000,
        "priceInfant": 461000,
        "displayIndex": 6,
        "capacity": 0
      },
      {
        "priceChild": 4912000,
        "priceAdult": 6522000,
        "priceInfant": 715000,
        "displayIndex": 7,
        "capacity": 9
      }
    ]

This is the sort function that I am using right now:

orderBy(results, 'displayIndex', 'asc');

I want to do something like this but this code will not work because the ternary operator will not run for every item:

orderBy(results, [this.capacity === 0 ? true : false, 'displayIndex'], ['asc', 'asc']);

Solution

  • Found out that there is a way to use functions inside orderby properties:

    orderBy(results, [function(resultItem) { return resultItem.capacity === 0; }, 'displayIndex'], ['asc', 'asc']);