我有一个对象数组,类型为fruit/ vegetable:
对于vegetable我所拥有的那种类型,我希望它是数组中的第一个项目,但我不知道如何使用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'}
];
Run Code Online (Sandbox Code Playgroud)
这是我尝试的小提琴:https: //jsfiddle.net/zg6js8af/
如何将类型vegetable作为数组中的第一项而不管其当前索引?
Ser*_*Pie 14
使用lodash _.sortBy.如果类型是蔬菜,它将首先排序,否则排序第二.
var items = [
{type: 'fruit', name: 'apple'},
{type: 'fruit', name: 'banana'},
{type: 'vegetable', name: 'brocolli'},
{type: 'fruit', name: 'cantaloupe'}
];
var sortedItems = _.sortBy(items, function(item) {
return item.type === 'vegetable' ? 0 : 1;
});
console.log(sortedItems);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)