Reputation: 8684
I have an array of objects, with their quantities (fruit_quantity
/vegetable_quantity
):
I am trying to sort by those quantities, so it shows the order from highest to lowest with lodash.
var items = [
{'type': 'fruit', 'name': 'apple', 'fruit_quantity': 20},
{'type': 'fruit', 'name': 'banana','fruit_quantity': 10},
{'type': 'vegetable', 'name': 'brocolli','vegetable_quantity': 15},
{'type': 'fruit', 'name': 'cantaloupe','fruit_quantity': 5}
];
var sortedItems = _.sortBy(items, ['fruit_quantity' || 'vegetable_quantity']).reverse();
I know that if they were the same key, like quantity
, then it will be done like this:
var sortedItems = _.sortBy(items, 'quantity').reverse();
But unfortunately I have to use different keys, but still sort with their respective quantity.
Here is a fiddle with my attempt: https://jsfiddle.net/zg6js8af/1/
How can I sort the items by their highest to lowest quantities?
This is what the final sort order should look like:
{'type': 'fruit', 'name': 'apple', 'fruit_quantity': 20},
{'type': 'vegetable', 'name': 'brocolli','vegetable_quantity': 15},
{'type': 'fruit', 'name': 'banana','fruit_quantity': 10},
{'type': 'fruit', 'name': 'cantaloupe','fruit_quantity': 5}
Upvotes: 2
Views: 433
Reputation: 192252
You just need to detect which property exists, and then return it. An example using Array#sort
:
var items = [
{'type': 'fruit', 'name': 'apple', 'fruit_quantity': 20},
{'type': 'fruit', 'name': 'banana','fruit_quantity': 10},
{'type': 'vegetable', 'name': 'brocolli','vegetable_quantity': 15},
{'type': 'fruit', 'name': 'cantaloupe','fruit_quantity': 5}
];
function getQuantity(item) {
return item.fruit_quantity || item.vegetable_quantity || 0;
}
items.sort(function(a, b) {
return getQuantity(a) - getQuantity(b);
});
console.log(items);
You can do the same with _.sortBy()
:
var items = [
{'type': 'fruit', 'name': 'apple', 'fruit_quantity': 20},
{'type': 'fruit', 'name': 'banana','fruit_quantity': 10},
{'type': 'vegetable', 'name': 'brocolli','vegetable_quantity': 15},
{'type': 'fruit', 'name': 'cantaloupe','fruit_quantity': 5}
];
function getQuantity(item) {
return item.fruit_quantity || item.vegetable_quantity || 0;
}
var result = _.sortBy(items, getQuantity);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Upvotes: 3