JSFiddle - React, Tailwind, and code Playground
JavaScript
function weightedNumSort(myArray,weightNum,weightString) {
var WEIGHTS_NUM = weightNum || [1,2,4,3]; //[YEAR,MONTH,DAY,COUNT], You can pass an array with appropriate weights for the number at the given position in the text, e.g year is the first Number
var WEIGHT_STRING = weightString || 1; //And a weight for the string value. If none get passed, default weights are used
function weightedSum (a,b,i) {
return ( a + b * ( WEIGHTS_NUM [i-1] || 1 ));
}
myArray = myArray.slice().sort(function (a, b) {
var reg = /(\d+)/g //A regex to extract the numerical part
var lNum = a.match(reg) //Extract the numerical parts we now have an array ["2013","09","26","2"]
var rNum = b.match(reg)
var delta = Array.apply(null,{length:lNum.length+1});
delta [0] = 0; //add a 0 at the beginning, for convenience with the reduce function
for (var i=0,j=lNum.length; i < j; i++) {
var value = lNum[i] - rNum[i];
value = ~~ (value / Math.abs (value)) // 1 for positive values, 0 for 0 , -1 for negative values, to make weighting easier
delta[i+1] = value;
}
var weightedNumValue = delta.reduce (weightedSum) //Put a weight on the number parts.
var weightedStrValue = WEIGHT_STRING * ( a > b ? 1 : a < b ? -1 : 0 )
return weightedNumValue + weightedStrValue //Add the weighted values and we have a positive or negative value with a correct weight on the numerical parts
})
return myArray
}
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'
];
console.log (
weightedNumSort (myArray)
) /*
[
"_aaaa_2013-09-25_ssss5.txt",
...