我如何用Lodash sortBy排序?

时间:2017-01-28 21:30:46

标签: javascript arrays lodash

我有一个类似下面的数组,我正在尝试使用lodash按价格对数组中的项目进行排序,但我认为它不起作用。请告诉我这里有什么问题,根据lodash文档,它将采用数组并应返回已排序的数组。

我的数据

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});

2 个答案:

答案 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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

根据source code,第二个参数应该是迭代数组。要解决此问题,您需要将匿名函数放在数组中,例如

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