Ваш JSON недействителен - если это фактические имена ключей строки JSON, необходимо заключить в кавычки. Вы прекратили закрытие] и}, и день рождения средней записи должен иметь какое-то значение, например, пустую строку или ноль - или просто не предоставлять этот ключ вообще. Я предполагаю, что вы можете это исправить и уже проанализировали JSON в переменную с именем json
.
Также вы не говорите, если даты в формате ДД / ММ (/ ГГГГ) или ММ / ДД (/ ГГГГ), поэтому я буду кодировать ДД / ММ, но вы можете закомментировать это, чтобы использовать ММ / ДД вместо.
«Ближайшая к текущей дате» неоднозначна: вчера ближе, чем на следующей неделе? Я предполагаю, что вчерашний день настолько далек от текущей даты, насколько это возможно.
Итак, ваш объект приведен в порядок вместе с процедурой сортировки. Я не проверял его, но даже если предположить, что он сломан, он должен дать вам общее представление:
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 doco .
.