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']);
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.
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.
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.
Found out that there is a way to use functions inside orderby properties:
orderBy(results, [function(resultItem) { return resultItem.capacity === 0; }, 'displayIndex'], ['asc', 'asc']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With