本文介绍了排序包含字符串,日期和数字数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
myarray的无功= [
_aaaa_2013-09-25_ssss9.txt',
_aaaa_2013-09-25_ssss8.txt',
_aaaa_2013-09-26_ssss1.txt',
_aaaa_2013-09-25_ssss10.txt',
_aaaa_2013-09-26_ssss2.txt',
_aaaa_2013-09-25_ssss13.txt',
_aaaa_2013-09-25_ssss5.txt',
_aaaa_2013-09-25_ssss6.txt',
_aaaa_2013-09-25_ssss7.txt
];
我需要按日期和编号的数组排序。
结果应该是
VAR的结果= [
_aaaa_2013-09-25_ssss5.txt',
_aaaa_2013-09-25_ssss6.txt',
_aaaa_2013-09-25_ssss7.txt',
_aaaa_2013-09-25_ssss8.txt',
_aaaa_2013-09-25_ssss9.txt',
_aaaa_2013-09-25_ssss13.txt',
_aaaa_2013-09-26_ssss1.txt',
_aaaa_2013-09-26_ssss2.txt
];
我已经试过低于code.this会做那种只有日期,但我需要在这之前,我.txt'.How可以做到这一点。
数排序 myArray.sort(功能(A,B){ VAR timestamp1与= a.substring(a.indexOf('_ AAAA')+ 6,a.indexOf('_ SSSS'));
VAR与timestamp2 = b.substring(b.indexOf('_ AAAA')+ 6,b.indexOf('_ SSSS'));
timestamp1与=新的日期(Date.UTC(timestamp1与[0],timestamp1与[1],timestamp1与[2]));
与timestamp2 =新的日期(Date.UTC(与timestamp2 [0],与timestamp2 [1],与timestamp2 [2])); 返回(timestamp1与>与timestamp2)? 1:(与timestamp2> timestamp1与-1:0);});
解决方案
您可以做到这一点是这样的:
VAR重= /^_aaaa_(\\d\\d\\d\\d-\\d\\d-\\d\\d)_ssss(\\d+)\\.txt$/;VAR的结果= myArray.slice()排序(功能(A,B){
变种AA = a.match(重),BB = b.match(重新);
返回(
AA [1]; BB [1]? -1:
AA [1]≥ BB [1]? 1:
氨基酸[2] - BB [2]
);
});
请注意使用 .slice()
来创建数组的一个副本。这可以,如果你想代替原来的数组进行排序可以省略。 (感谢@DerFlatulator的提醒!)
var myArray = [
'_aaaa_2013-09-25_ssss9.txt',
'_aaaa_2013-09-25_ssss8.txt',
'_aaaa_2013-09-26_ssss1.txt',
'_aaaa_2013-09-25_ssss10.txt',
'_aaaa_2013-09-26_ssss2.txt',
'_aaaa_2013-09-25_ssss13.txt',
'_aaaa_2013-09-25_ssss5.txt',
'_aaaa_2013-09-25_ssss6.txt',
'_aaaa_2013-09-25_ssss7.txt'
];
I need to sort the array by date and number.
Result should be
var result = [
'_aaaa_2013-09-25_ssss5.txt',
'_aaaa_2013-09-25_ssss6.txt',
'_aaaa_2013-09-25_ssss7.txt',
'_aaaa_2013-09-25_ssss8.txt',
'_aaaa_2013-09-25_ssss9.txt',
'_aaaa_2013-09-25_ssss13.txt',
'_aaaa_2013-09-26_ssss1.txt',
'_aaaa_2013-09-26_ssss2.txt'
];
I have tried below code.this will do the sort by date only but i need to sort by the number which is before '.txt'.How can i do this.
myArray.sort(function (a, b) {
var timeStamp1 = a.substring(a.indexOf('_aaaa') + 6, a.indexOf('_ssss'));
var timeStamp2 = b.substring(b.indexOf('_aaaa') + 6, b.indexOf('_ssss'));
timeStamp1 = new Date(Date.UTC(timeStamp1[0], timeStamp1[1], timeStamp1[2]));
timeStamp2 = new Date(Date.UTC(timeStamp2[0], timeStamp2[1], timeStamp2[2]));
return (timeStamp1 > timeStamp2) ? 1 : (timeStamp2 > timeStamp1 ? -1 : 0);
});
解决方案
You could do it like this:
var re = /^_aaaa_(\d\d\d\d-\d\d-\d\d)_ssss(\d+)\.txt$/;
var result = myArray.slice().sort( function( a, b ) {
var aa = a.match(re), bb = b.match(re);
return(
aa[1] < bb[1] ? -1 :
aa[1] > bb[1] ? 1 :
aa[2] - bb[2]
);
});
Note the use of .slice()
to create a copy of the array. This can be omitted if you want to sort the original array in place. (Thanks to @DerFlatulator for the reminder!)
这篇关于排序包含字符串,日期和数字数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!