I have an array of objects, with type of fruit
/vegetable
:
For the one type vegetable
I have, I want it to be the first item in the array, but I am not sure how to do so with lodash.
var items = [
{'type': 'fruit', 'name': 'apple'},
{'type': 'fruit', 'name': 'banana'},
{'type': 'vegetable', 'name': 'brocolli'}, // how to make this first item
{'type': 'fruit', 'name': 'cantaloupe'}
];
Here is a fiddle with my attempt: https://jsfiddle.net/zg6js8af/
How can I get type vegetable
to be the first item in the array regardless of its current index?
Using lodash _.sortBy. If the type is vegetable, it will be sorted first, otherwise second.
let items = [
{type: 'fruit', name: 'apple'},
{type: 'fruit', name: 'banana'},
{type: 'vegetable', name: 'brocolli'},
{type: 'fruit', name: 'cantaloupe'},
];
let sortedItems = _.sortBy(items, ({type}) => type === 'vegetable' ? 0 : 1);
console.log(sortedItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Here is another solution without using lodash.
function sortBy(array, fn) {
return array.map(v => [fn(v), v]).sort(([a], [b]) => a - b).map(v => v[1]);
}
let items = [
{type: 'fruit', name: 'apple'},
{type: 'fruit', name: 'banana'},
{type: 'vegetable', name: 'brocolli'},
{type: 'fruit', name: 'cantaloupe'},
];
let sortedItems = sortBy(items, ({type}) => type === 'vegetable' ? 0 : 1);
console.log(sortedItems);
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