gpt4 book ai didi

javascript - 对具有年份和月份的字符串数组进行排序

转载 作者:行者123 更新时间:2023-11-30 16:08:47 25 4
gpt4 key购买 nike

我有一个像下面这样的数组

var testArr = ["2009-feb", "2009-jan", "2010-mar", "2010-jan", "2011-jul", "2011-sep", "2011-jan", "2012-jan", "2012-dec", "2012-feb", "2013-may", "2013-jul", "2013-jun", "2014-jan", "2014-dec", "2014-may", "2015-may", "2015-jan", "2015-jun", "2016-jan", "2016-dec"];

我需要对它们进行排序

var sortOrder="asc";
testArr.sort(function (a, b) {
if (sortOrder == "asc") {
return a.localeCompare(b);
}
else {
return b.localeCompare(a);
}
});

输出是

["2009-feb","2009-jan","2010-jan","2010-mar","2011-jan","2011-jul","2011-sep","2012-dec","2012-feb","2012-jan","2013-jul","2013-jun","2013-may","2014-dec","2014-jan","2014-may","2015-jan","2015-jun","2015-may","2016-dec","2016-jan"]   

这是错误的。

最佳答案

我想你的意思是按日期排序

testArr.sort(function(dateA, dateB) {
return new Date(dateA) - new Date(dateB)
})

如果你想要它最新鲜的日期,首先将 dateA 与 dateB 翻转。

在tonic上运行示例: https://tonicdev.com/lipp/sort-dates

关于javascript - 对具有年份和月份的字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596786/

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