[英]Javascript - Sort months array in chronological order basis current month
[英]Javascript sort array of objects in reverse chronological order
我有一個包含作業列表的對象數組,並且我想按相反的時間順序對它們進行排序,例如它們會出現在簡歷中。 我想出了下面的“似乎”可行的解決方案,但我想知道是否有更好的方法可以做到。
我從服務器獲取的數據采用以下格式。
// ms=> monthStart me=>monthEnd etc...
var jobs = [
{
ms: 06,
ys: 2013,
me: 02,
ye: 2015
},
{
ms: 09,
ys: 2013,
me: 02,
ye: 2014
},
{
ms: 08,
ys: 2000,
me: 06,
ye: 2016
},
{
ms: 01,
ys: 2014,
me: 02,
ye: 2017
}
];
我想出了為每個項目添加時間順序哈希值的函數。
var args = {
monthStart: 'ms',
yearStart: 'ys',
monthEnd: 'me',
yearEnd: 'ye'
};
function createItemTimeOrder(item, args) {
var monthStart = item[args.monthStart] || 0,
yearStart = item[args.yearStart] || 0,
monthEnd = item[args.monthEnd] || 0,
yearEnd = item[args.yearEnd] || 0;
// present if end month and end year are empty
(monthEnd && yearEnd) || (monthEnd = 12, yearEnd = 3000);
// weights yearEnd > monthEnd > yearStart > monthStart
item._timeorder =
monthStart + (yearStart * 2) +
((monthEnd + yearEnd) * 2) +
(yearEnd * 4);
}
//add _timeorder proptery
jobs.forEach(function (job) {
createItemTimeOrder(job, args);
});
// sortby timer order in in reverse chronological order
jobs.sort(function (job1, job2) {
return job2._timeorder - job1._timeorder;
});
正如PM 77-1所建議的那樣,請考慮將內置的Array.prototype.sort與Date對象一起使用。 大概您想按開始或結束之一對它們進行排序:
jobs.sort(function(a, b) {
return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.