麻烦排序json对象最接近当前日期与一些值未定义



我从Facebook返回一个json对象,其中包含一些好友信息。

一些用户包含了他们的生日,一些用户没有,而另一些用户只包含了月份和日期。

我想对数组进行排序,将生日与当前日期接近的用户放在第一位。

我该怎么做?

json对象是这样的:

json = { "data" : [{name : "Joe Sam", id : "5555555", birthday: "02/02/1989" }, {name : "Joe Sam", id : 5555555, birthday:  }, {name : "Joe Sam", id : 5555555, birthday: "01/01" }

您的JSON无效-如果这是实际的JSON字符串关键字需要引号。省略了结束的]和},中间记录的生日必须有某种值,例如,空字符串或null -或者根本不提供该键。我假设您可以解决这个问题,并且已经将JSON解析为一个名为json的变量。

你也没有说日期是DD/MM(/YYYY)格式还是MM/DD(/YYYY)格式,所以我将编码为DD/MM,但你可以注释掉,使用MM/DD。

"最接近当前日期"有歧义:昨天比下周更接近吗?我就假定昨天是你所能得到的离现在最远的日期了。

这就是你的对象和一个排序例程。我还没有测试它,但即使假设它坏了,它也应该给你一个大致的想法:

var json = { "data" : [
                {name : "Joe Sam", id : "5555555", birthday: "02/02/1989" },
                {name : "Joe Sam", id : 5555555, birthday: null },
                {name : "Joe Sam", id : 5555555, birthday: "01/01" }
             ]
           };
// First sort into ascending birthday order, with people who didn't provide
// a birthday at the beginning of the list
function dayMonthComparer(a,b)
  // note double-equals null also allows for undefined "birthday" property 
  if (aBD == null)
    return bBD == null ? 0 : -1;
  if (bBD == null)
    return 1;
  // next two lines allow for DD/MM format; comment them out for MM/DD format
  aBD = aBD.substr(3,2) + aBD.substr(0,2);
  bBD = bBD.substr(3,2) + bBD.substr(0,2);
  // note: simple string compare works once in MM/DD format
  return aBD === bBD ? 0 : (aBD > bBD ? 1 : -1);
}
json["data"].sort(function(a,b) {
  return dayMonthComparer(a["birthday"],b["birthday"]);
});
// Next, find the first item in the array after the current date and
// move everything before that item to the end of the array.
var today = new Date(),
    d = today.getDate(),
    m = today.getMonth() + 1,
    current,
    firstNonBlank = null,
    firstFromCurrent = 0;
if (d < 10) d = "0" + d;
if (m < 10) d = "0" + d;
current = d + "/" m;
// or use current = m + "/" + d if using American format
// get index of first item with birthday on or after current date
while(firstFromCurrent < json["data"].length &&
      dayMonthComparer(current,json["data"][firstFromCurrent]["birthday"]) > 1) {
  if (firstNonBlank===null &&
      json["data"][firstFromCurrent]["birthday"] != null)
     firstNonBlank = firstFromCurrent;
  firstFromCurrent++;
}
if (firstFromCurrent < json["data"].length) {
  json["data"] = json["data"].slice(firstFromCurrent)
                 .concat(json["data"].slice(firstNonBlank,firstFromCurrent),
                         json["data"].slice(0,firstNonBlank) );
}
// array is now sorted by birthday starting from current date, where
// those who didn't provide a birthday are at the end

.sort()的工作原理请参考MDN文档

最新更新