Array with object sorting with Underscore sortBy

后端 未结 3 365
滥情空心
滥情空心 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.

提交回复
热议问题