Javascript 在多维数组中按日期字符串对数组排序
我有一个多维数组,其中有一个值date,我想根据这个值对它进行排序,下面是数组结构:Javascript 在多维数组中按日期字符串对数组排序,javascript,jquery,arrays,Javascript,Jquery,Arrays,我有一个多维数组,其中有一个值date,我想根据这个值对它进行排序,下面是数组结构: [ ['01-Sep-2018', 'Some other Value'], ['20-Aug-2018', 'Some other Value'], ['21-Aug-2018', 'Some other Value'], ['22-Aug-2018', 'Some other Value'], ['23-Aug-2018', 'Some other Value'] ]
[
['01-Sep-2018', 'Some other Value'],
['20-Aug-2018', 'Some other Value'],
['21-Aug-2018', 'Some other Value'],
['22-Aug-2018', 'Some other Value'],
['23-Aug-2018', 'Some other Value']
]
我需要这样的输出
[
['20-Aug-2018', 'Some other Value'],
['21-Aug-2018', 'Some other Value'],
['22-Aug-2018', 'Some other Value'],
['23-Aug-2018', 'Some other Value'],
['01-Sep-2018', 'Some other Value']
]
下面是您期望的工作代码
compare_dates = function(date1,date2){
d1= new Date(date1[0]);
d2= new Date(date2[0]);
if (d1>d2) return 1;
else if (d1<d2) return -1;
else return 0;
}
var objs = [
['01-Sep-2018', 'Some other Value'],
['20-Aug-2018', 'Some other Value'],
['21-Aug-2018', 'Some other Value'],
['22-Aug-2018', 'Some other Value'],
['23-Aug-2018', 'Some other Value']
];
objs.sort(compare_dates);
console.log(objs);
您可以使用Array.sort进行此操作,唯一复杂的是将日期转换为JS可以解析的内容。这可以通过将日期中的-替换为空格来实现,将它们转换为类似“2018年9月20日”的内容,这可以作为日期构造函数的输入
让数组=[
['01-Sep-2018','其他价值',
[‘2018年8月20日’,‘其他价值’,
['2018年8月21日','其他价值',
[‘2018年8月22日’,‘其他价值’,
['2018年8月23日','其他价值'
];
array.sorta,b=>new Datea[0]。replace/-/g',-new Dateb[0]。replace/-/g';
console.logarray 您可以使用和来提取日期值:
const data=['01-Sep-2018'、['20-Aug-2018'、['21-Aug-2018'、[22-Aug-2018'、[23-Aug-2018'、[23-Aug-2018'、[21-Aug-2018'、[21-Aug-2018'、[22-Aug-2018'、[23-Aug-2018]、[23-Aug-other-Value'];
const sorted=data.sorta,b=>{
常量[aD,bD]=[a,b]。映射[d]=>新日期。替换/-/gi,'
返回aD-bD;
};
console.logsorted;可能重复的