How to use Lodash orderby with a custom function?
Asked Answered
M

2

15

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']);
Marriageable answered 2/9, 2018 at 7:49 Comment(5)
Please share the code you are currently using to sort the Array and what you have tried to add the condition.Dennard
I don't think you can do that without changing the original object or adding a new property. You do not have capacity key inside you array of objects, so how did you expect to sort by it?Mccaslin
I have the capacity (corrected the sample data). @LazarNikolicMarriageable
Than do this orderBy(results, 'capacity', 'desc');Mccaslin
I want to sort them by both properties(displayIndex and capacity). Only prioritize the available (capacity > 0) items first. @LazarNikolicMarriageable
M
34

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

orderBy(results, [function(resultItem) { return resultItem.capacity === 0; }, 'displayIndex'], ['asc', 'asc']);
Marriageable answered 2/9, 2018 at 8:40 Comment(0)
H
0

@Saeed is right, though it's a bit more succinct to use an arrow function:

orderBy(results, [(resultItem) => resultItem.capacity === 0, 'displayIndex'],['asc', 'asc']);
Hexosan answered 13/4 at 21:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.