【问题标题】:How do I sort with Lodash sortBy?如何使用 Lodash sortBy 进行排序?
【发布时间】:2017-01-28 21:30:46
【问题描述】:

我有一个类似下面的数组,我正在尝试使用 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});

【问题讨论】:

  • 它在做什么?
  • 你用的是什么版本的lodash?

标签: javascript arrays lodash


【解决方案1】:

您很可能使用的是旧版本的 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>

【讨论】:

  • @ruakh 谢谢,我已经更新了答案以包含它
  • 我已经更新了我的答案以包含一个有效的 sn-p。很可能是 lodash 的版本。
【解决方案2】:

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

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

【讨论】:

  • 请扩展此答案以显示正确实施的示例。
  • 感谢大家的回复,但不幸的是,即使按照上面的方式修改了我的代码,它仍然没有返回排序后的数组,而是将数组原样返回给我。
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多