gpt4 book ai didi

javascript - 按日期 DD/MM/YY 格式对 JS 数组进行排序

转载 作者:行者123 更新时间:2023-12-03 09:30:15 25 4
gpt4 key购买 nike

我有这种类型的刺痛:

12/07/2015|评论1,11/09/2015|评论2,31/07/2015|评论3,30/07/2015|评论4, 16/07/2015|评论5,09/07/2015|评论6,"

我正在努力实现这个结果:

2015年9月7日|评论6,2015年7月12日|评论1,2015年7月16日|评论5,2015年7月30日|评论4,2015年7月31日|评论3,2015年9月11日|评论2 ,

到目前为止我的代码如下所示:

function rearangeDates(old_order){

var list = old_order.split(',');
list = list
.map( // for each element in the list (each date)
function(val,idx){
// use the first part(before the dot(.)), replace the - with spaces and convert to date
console.log(val.split('|')[0].split("/").join("-"))
return new Date(val.split('|')[0].split("/").join("-").replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );
})
.sort(); // at the end sort the results.
console.log(list)
}

我的主要目标是安排日期,但此函数的结果是:

[ Fri Jul 31 2015 00:00:00 GMT+0300 (FLE Daylight Time), Fri Sep 11 2015 00:00:00 GMT+0300 (FLE Daylight Time) -> This should be at the end of the array since Sep is after Jul, Invalid Date, Sun Jul 12 2015 00:00:00 GMT+0300 (FLE Daylight Time), Thu Jul 09 2015 00:00:00 GMT+0300 (FLE Daylight Time), Thu Jul 16 2015 00:00:00 GMT+0300 (FLE Daylight Time), Thu Jul 30 2015 00:00:00 GMT+0300 (FLE Daylight Time)]

最佳答案

您需要将比较函数传递给您的 sort :

.sort(function(a, b){
return a.getTime() - b.getTime();
})

这应该按正确的顺序对您的日期进行排序。

sort 将根据该函数的返回值对 2 个传递的值进行排序:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

关于javascript - 按日期 DD/MM/YY 格式对 JS 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31532914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com