How to sort objects by date ascending order?

后端 未结 4 1585
孤街浪徒
孤街浪徒 2021-02-10 08:09

if I have a list of object:

var objectList= LIST_OF_OBJECT;

each object in the list contains three attributes: \"name<

相关标签:
4条回答
  • 2021-02-10 08:38

    The Array.sort method accepts a sort function, which accepts two elements as arguments, and should return:

    • < 0 if the first is less than the second
    • 0 if the first is equal to the second
    • > 0 if the first is greater than the second.

    .

    objectList.sort(function (a, b) {
        var key1 = a.date;
        var key2 = b.date;
    
        if (key1 < key2) {
            return -1;
        } else if (key1 == key2) {
            return 0;
        } else {
            return 1;
        }
    });
    

    You're lucky that, in the date format you've provided, a date that is before another date is also < than the date when using string comparisons. If this wasn't the case, you'd have to convert the string to a date first:

    objectList.sort(function (a, b) {
        var key1 = new Date(a.date);
        var key2 = new Date(b.date);
    
        if (key1 < key2) {
            return -1;
        } else if (key1 == key2) {
            return 0;
        } else {
            return 1;
        }
    });
    
    0 讨论(0)
  • 2021-02-10 08:38

    You can try:

    <script src="https://cyberknight.000webhostapp.com/arrange.js">
    var a =[-1,0,5,4,3,2,6,1,1];
    var b = totzarrange(a)
    console.log(b);
    </script>
    
    0 讨论(0)
  • 2021-02-10 08:44
    yourArray.sort(function(a, b) { 
     a = new Date(a.date);
     b = new Date(b.date);
     return a >b ? -1 : a < b ? 1 : 0;
    })
    
    0 讨论(0)
  • 2021-02-10 08:54

    If your objects have the date information within a String field:

    yourArray.sort(function(a, b) { return new Date(a.date) - new Date(b.date) })
    

    or, if they have it within a Date field:

    yourArray.sort(function(a, b) { return a.date - b.date })
    
    0 讨论(0)
提交回复
热议问题