gpt4 book ai didi

javascript - JS - 将字符串数组按日期排序

转载 作者:行者123 更新时间:2023-11-29 23:06:13 25 4
gpt4 key购买 nike

我有以下数组:

let datas = ["nov/2018", "set/2018", "jan/2019", "dez/2018", "out/2018"]

当我执行

datas.sort()

他按字母顺序排序,而我必须先按年份排序,然后再按字母顺序排序。

["dez/2018", "jan/2019", "nov/2018", "out/2018", "set/2018"]

今天测试我得到了以下代码行:

var datas = ["mar", "abr", "jan", "dez", "set", "mai", "jun", "out", "jul"];
var datas_corretas = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"];
var result = [];

datas_corretas.forEach(function ordenar(element, index){
var mes = datas.filter(function(valor){
return valor == datas_corretas[index];
});
result.push(mes[0]);
for(element of result){
if (element === undefined || element === null){
result.pop(element);
}
}
});
console.log(result);

这样我可以对数据进行排序,但问题是当我将它与年份一起使用时

var datas = ["mar/2018", "abr/2018", "jan/2019", "dez/2018", "set/2018", "mai/2018", "jun/2018 ", "out/2018", "jul/2018"];

有人知道我该如何解决这个问题吗?

最佳答案

您可以拆分日期并先按年份排序,然后按月份索引排序。

var months = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"],
datas = ["nov/2018", "set/2018", "jan/2019", "dez/2018", "out/2018"];

datas.sort((a, b) => {
var aa = a.split('/'),
bb = b.split('/');
return aa[1] - bb[1] || months.indexOf(aa[0]) - months.indexOf(bb[0]);
});

console.log(datas);

为了更快地访问,您可以将月份存储为对象。

var months = { jan: 1, fev: 2, mar: 3, abr: 4, mai: 5, jun: 6, jul:7, ago: 8, set: 9, out: 10, nov: 11, dez: 12 },
datas = ["nov/2018", "set/2018", "jan/2019", "dez/2018", "out/2018"];

datas.sort((a, b) => {
var aa = a.split('/'),
bb = b.split('/');
return aa[1] - bb[1] || months[aa[0]] - months[bb[0]];
});

console.log(datas);

关于javascript - JS - 将字符串数组按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54715658/

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