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);
});
This, extracts the numbers from the given string, and puts a given weight on each numerical part. So you can sort it in any order with given priorities for Count, Day, Month, Year.
Output
and a Fiddle
This worked for me.
jsFiddle
Sort by numeric value within strings.
This assumes:
["aa_123","aa_13","aa_2","aa_22_bb_23","aa_22_bb_3"].sort( function ( a , b ) {
} );
result:
You could do it like this:
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!)