如何按日期升序对对象进行排序?

编程入门 行业动态 更新时间:2024-10-23 03:28:37
本文介绍了如何按日期升序对对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有对象列表:

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

更多推荐

如何按日期升序对对象进行排序?

本文发布于:2023-11-29 00:51:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:升序   对象   按日

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!