我需要以DD-MMMM-YYYY格式按递增和放大的方式对给定的日期数组进行排序。通过Javascript函数降序数组&使用静态定义的数组断言此结果。下面是我尝试的代码,但似乎部分工作:
it("Sorting DD-MMMM-YYYY Arrays",function(){
var unsorted_array1=['25-Nov-2005','04-Aug-2015','04-Aug-2015','30-Jun-2006','26-Jun-2013','27-Jun-2013','15-Feb-2001','10-Jul-2012','29-May-2012'];
var unsorted_array2=['25-Nov-2005','04-Aug-2015','04-Aug-2015','30-Jun-2006','26-Jun-2013','27-Jun-2013','15-Feb-2001','10-Jul-2012','29-May-2012'];
var arraytobecompared_desc=['04-Aug-2015','04-Aug-2015','27-Jun-2013','26-Jun-2013','10-Jul-2012','29-May-2012','30-Jun-2006','25-Nov-2005','15-Feb-2001'];
var arraytobecompared_asc=['15-Feb-2001','25-Nov-2005','30-Jun-2006','29-May-2012','10-Jul-2012','26-Jun-2013','27-Jun-2013','04-Aug-2015','04-Aug-2015'];
var sorted_with_function_ascending= unsorted_array1.sort(function(a, b){
var aa = a.split('-').reverse().join(),
bb = b.split('-').reverse().join();
return aa < bb ? -1 : (aa > bb ? 1 : 0);
});
var sorted_with_function_descending= unsorted_array2.sort(function(a, b){
a = a.split('-');
b = b.split('-');
return b[2] - a[2] || b[1] - a[1] || b[0] - b[0];
});
console.log("Ascending dates- "+sorted_with_function_ascending);
console.log("Descending dates- "+sorted_with_function_descending);
expect(arraytobecompared_desc).toEqual(sorted_with_function_descending);
expect(arraytobecompared_asc).toEqual(sorted_with_function_ascending);
})
升序&amp;降序函数返回中间值排序不正确,导致expect块失败。
答案 0 :(得分:0)
以下是我提出的建议:
let unsorted_array = ['25-Nov-2005','05-Aug-2015','04-Aug-2015','30-Jun-2006','26-Jun-2013','27-Jun-2013','15-Feb-2001','10-Jul-2012','29-May-2012']
var sortable = [];
unsorted_array.forEach(date => {
sortable.push([ date, new Date(date).getTime() ]);
})
sortable.sort( (a, b) => a[1] - b[1] )
let sorted_array = sortable.map(arr => arr[0])
console.log(sorted_array)
我正在构建一个包含以下内容的数组:
[
["date", "corresponding timestamp"],
["date", "corresponding timestamp"]
]
然后我按时间戳( (a, b) => a[1] - b[1] )
然后我用地图(arr => arr[0])
输出结果为:
["15-Feb-2001", "25-Nov-2005", "30-Jun-2006", "29-May-2012", "10-Jul-2012", "26-Jun-2013", "27-Jun-2013", "04-Aug-2015", "05-Aug-2015"]
对于降序,请将a[1] - b[1]
替换为b[1] - a[1]
。