如何按日期升序对对象进行排序? [英] How to sort objects by date ascending order?

查看:117
本文介绍了如何按日期升序对对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有对象列表:

var objectList= LIST_OF_OBJECT;

列表中的每个对象包含三个属性:"名称","日期","性别 "

each object in the list contains three attributes: "name", "date","gender"

如何按"日期"属性的升序对列表中的对象进行排序?

How to sort the objects in the list by "date" attribute ascending order?

("日期"属性包含类似于"2002-08-29 21:15:31 + 0500"的字符串值)

(the "date" attribute contain string value like "2002-08-29 21:15:31+0500")

推荐答案

Array.sort 方法接受一个sort函数,该函数接受两个元素作为参数,并应返回:

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

  • <如果第一个小于第二个,则为0
  • 如果第一个等于第二个,则为0
  • >如果第一个大于第二个,则为0.

.

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;
    }
});

这篇关于如何按日期升序对对象进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆