简体   繁体   中英

How do I sort with Lodash sortBy?

I've an array like the one below and I'm trying to sort the items in the array by its price using lodash, but I don't see it working. Please let me know what is wrong here, as per the lodash documentation it will take an array and should return the sorted array.

My data

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
  }
]

Sort code

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

Most likely you're using an older version of Lodash. It works with 4.17.2 as demonstrated below.

 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> 

According to the source code , the second argument should be an array of iteratees. To fix the problem you need to put your anonymous function inside an array, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM