2017-06-09 47 views
1

我有對象的數組,有型的fruit/vegetablelodash - 將對象移動到數組中的第一位?

對於一個類型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'} 
]; 

這裏是我的嘗試小提琴: https://jsfiddle.net/zg6js8af/

我怎樣才能類型vegetable是數組中的第一個項目,無論其當前索引的?

回答

4

使用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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

+0

工程就像一個魅力,謝謝:) – Wonka

1

爲什麼在不需要它時使用lodash(並且可以使用單個的reduce編寫功能代碼)?

var items = [ 
    {'type': 'fruit', 'name': 'apple'}, 
    {'type': 'fruit', 'name': 'banana'}, 
    {'type': 'vegetable', 'name': 'brocolli'}, 
    {'type': 'fruit', 'name': 'cantaloupe'} 
]; 

var final = items.reduce(function(arr,v) { 
    if (v.type === 'vegetable') return [v].concat(arr) 
    arr.push(v) 
    return arr 
},[]); 
alert(JSON.stringify(final)); 
+0

感謝您對另一種方法,upvoted :)我使用lodash在很多地方已經和喜歡它的簡潔的語法是誠實的;即使當最終目標是一樣的:) – Wonka

1

您可以通過排序在type方向desc做到這一點:

var res = _.orderBy(items, ['type'], ['desc']); 

或使用partition

var res = _.chain(items) 
    .partition({type: 'vegetable'}) 
    .flatten() 
    .value(); 
+0

謝謝,但我試圖得到它的工作基於'蔬菜'的實際值'===',所以它是靈活的:) – Wonka

+0

@Wonka看着我編輯的答案 – stasovlas

+0

再次感謝,但我去'_.sortBy'因爲它是一個單一的方法:) – Wonka

相關問題