使用日期和字符串angularjs对对象数组进行排序

时间:2017-03-09 02:47:28

标签: javascript angularjs sorting

我有一个就业记录对象数组,让我们说它有这个记录:

gform.submit.success

如果我想在最近的事情中对此进行排序:

var records = [
        {name: "Sample",  monthTo: "NOV", yearTo: "1960"},
        {name: "Sample2",  monthTo: "JAN", yearTo: "2016"},
        {name: "Sample3",  monthTo: "DEC", yearTo: "2017"},
    ];

这样可行,但如果我有function sortEmpHistoryByLatest(){ records.sort(function(a,b) { var aDate = new Date(a.getYearTo()+"-"+a.getMonthTo()+"-01").getDate(); var bDate = new Date(b.getYearTo()+"-"+b.getMonthTo()+"-01").getDate(); return aDate - bDate }); } 作为记录而不是月份或年份格式怎么办?让我们说:

Present

如何将var records2 = [ {name: "Sample", monthTo: "NOV", yearTo: "1960"}, {name: "Sample2", monthTo: "Present", yearTo: "Present"}, {name: "Sample3", monthTo: "DEC", yearTo: "2017"}, ]; 放在列表中的第一位呢?

2 个答案:

答案 0 :(得分:0)

您可以将数组拆分为两个数组 - 一个只有日期,另一个用"存在"分数。然后只对第一个数组进行排序并合并它们。

您可以使用下一个代码拆分它们:

var records_with_dates = records.filter(function(record){return record.monthTo!=='Present';});
var sorted_records_with_dates = records_with_dates.sort(// your sort func);
var present_records = records.filter(function(record){return record.monthTo==='Present';});

var sorted_records = present_records.concat(sorted_records_with_dates);

答案 1 :(得分:0)

您可以执行以下操作:将precent替换为当前年份和月份。

您可以结帐工作plunker

var sorted;
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var today = new Date();
var mm = today.getMonth();
var yyyy = today.getFullYear();
var mmStr = months[mm];
console.log('currentMonth:' + mmStr)

function sortEmpHistoryByLatest() {
  sorted = records.sort(function(a, b) {

    var monthA = a.monthTo == "Present" ? mm : months.indexOf(a.monthTo);
    var yearA = a.yearTo == "Present" ? yyyy : a.yearTo;
    var monthB = b.monthTo == "Present" ? mm : months.indexOf(b.monthTo);
    var yearB = b.yearTo == "Present" ? yyyy : b.yearTo;

    var aDate = new Date(yearA, monthA);
    var bDate = new Date(yearB, monthB); 
    console.log('A'+aDate+' yearMonth'+yearA+''+monthA);
    console.log('B'+aDate+' yearMonth'+yearB+''+monthB)
    return bDate - aDate; //Ascending  order
    //return aDate - bDate;//for Descending  order
  });
}