Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']);
like image 914
Saeed Avatar asked Sep 02 '18 07:09

Saeed


People also ask

How do you use orderBy Lodash?

orderBy() method is similar to _. sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort.

Does Lodash groupBy preserve order?

groupBy , but it does preserve the order of array-like collections, and that's probably unlikely to change. So the sub-items within groups would retain their original ordering, but the grouped key ordering may change, because they are object properties.

Is Lodash efficient?

Lodash is extremely well-optimized as far as modern JS goes, but, as you may know, nothing can be faster than native implementation. Even if Lodash uses the same API under-the-hood, function call overhead is still present. Some might say that these are just some micro-optimizations.


1 Answers

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

orderBy(results, [function(resultItem) { return resultItem.capacity === 0; }, 'displayIndex'], ['asc', 'asc']);
like image 146
Saeed Avatar answered Nov 12 '22 21:11

Saeed