2017-01-28 21 views
0

我有一個像下面這樣的數組,我試圖按照它的價格使用lodash對數組中的項進行排序,但我沒有看到它的工作。請讓我知道這裏有什麼問題,根據lodash文檔,它將採用一個數組並且應該返回排序後的數組。我如何分類與Lodash sortBy?

我的數據

var items= [ 
    { 
    "total": 11, 
    "productGroup": { 
     "_id": "5834754f0acc770ce14b1378", 
     "name": "Auto Biography", 
     "description": "Yum", 
     "type": "book" 
    },  
    "_id": "58791af46c698c00475e7f41",  
    "price": 200, 
    "sold": 0 
    }, 
    { 
    "total": 11, 
    "productGroup": { 
     "_id": "5834754f0acc770ce14b1378", 
     "name": "Science Fiction", 
     "description": "Yum", 
     "type": "book" 
    },  
    "_id": "58791af46c698c00475e7f41",  
    "price": 120, 
    "sold": 0 
    }, 
    { 
    "total": 11, 
    "productGroup": { 
     "_id": "5834754f0acc770ce14b1378", 
     "name": "Language", 
     "description": "Yum", 
     "type": "book" 
    },  
    "_id": "58791af46c698c00475e7f41",  
    "price": 125, 
    "sold": 0 
    }, 
    { 
    "total": 11, 
    "productGroup": { 
     "_id": "5834754f0acc770ce14b1378", 
     "name": "Fiction", 
     "description": "Yum", 
     "type": "book" 
    },  
    "_id": "58791af46c698c00475e7f41",  
    "price": 300, 
    "sold": 0 
    } 
] 

排序代碼

items = _.sortBy(items, item=>{return item.price}); 
+0

它正在做什麼呢? – Soviut

+0

你使用的是什麼版本的lodash? – Soviut

回答

1

根據該source code,第二個參數應該是iteratees的陣列。要解決此問題,需要將匿名函數放入數組中,例如

items = _.sortBy(items, [item=>{return item.price}]); 
+2

請在此答案上展開以顯示正確實施的示例。 – Soviut

+0

感謝大家的迴應,但不幸的是,即使在修改上面的代碼之後,它仍然沒有返回排序後的數組,它仍然按原樣返回數組。 –

2

最有可能你正在使用Lodash的舊版本。它適用於4.17.2,如下所示。

var items = [ 
 
    { 
 
    "_id": "58791af46c698c00475e7f41",  
 
    "price": 200 
 
    }, 
 
    { 
 
    "_id": "58791af46c698c00475e7f41",  
 
    "price": 120 
 
    }, 
 
    { 
 
    "_id": "58791af46c698c00475e7f41",  
 
    "price": 125 
 
    }, 
 
    { 
 
    "_id": "58791af46c698c00475e7f41",  
 
    "price": 300 
 
    } 
 
]; 
 

 
var results = _.sortBy(items, item => item.price); 
 
console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

+0

@ruakh謝謝,我已經更新了包含該答案的 – Soviut

+0

我已更新我的答案以包含工作片段。最有可能的是lodash的版本。 – Soviut