Array with object sorting with Underscore sortBy

后端 未结 3 350
滥情空心
滥情空心 2020-12-24 04:49

I have this array. How do I use underscore \'_.sortBy\' to sort it according to start date?

[
    { 
        id: \'oljw832021kjnb389xzll323jk\',
        star         


        
相关标签:
3条回答
  • 2020-12-24 05:01

    I did it this way:

    var sorted = _(list).sortBy(
                        function (item) {                        
                            return [new Date(item.effectiveDate).getTime(), item.batchId];
                        }), "batchId");
    

    If you want it descending then it's the same thing but *-1

    var sorted = _(list).sortBy(
                        function (item) {                        
                            return [new Date(item.effectiveDate).getTime()*-1, item.batchId];
                        }), "batchId");
    

    In this example I am ordering by two fields, you can forget about the item.batchId.

    Hope this helps someone.

    0 讨论(0)
  • 2020-12-24 05:02

    Use an iterator function, not a single string for a property:

    _.sortBy(arr, function(o) { return o.start.dateTime; })
    
    0 讨论(0)
  • 2020-12-24 05:22

    var sortedItem = _.sortBy(yourArrayName, ["start"])

    0 讨论(0)
提交回复
热议问题