简体   繁体   中英

How sort this array of items by date in desc order (I used loadash sortBy but it returns oldest first while I need newest first)?

How can I sort this array of objects with dates using desc order?

I tried loadsh sortBy

  if ( sort && sort == "new") {
      items = _.sortBy(items, (dateObj) => {
      return new Date(dateObj.pubDate);
      });
      }

But it returns oldest items first while I need newest first. How can be it fixed?

Since your are already using lodash, the solution is simple and involve just a minimal modification to your current code:

items = _.orderBy(items, (dateObj) => {
      return new Date(dateObj.pubDate);
      }, 'desc');  

lodash orderBy is very similar to sortBy with the addition of a third parameter, which specify the sort order (asc or desc), and the difference that the 'iteratee' could also be 'iteratees', by specifying an array of properties to sort by, in which case the sort order could also be an array with corresponding order strings for each property.

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