Skip to content Skip to sidebar Skip to footer

Sorting An Array Which Contains String, Date And Number

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

Solution 1:

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!)

Solution 2:

This worked for me.

myArray.sort(function (a, b) {
    var a_s = a.substring(0, a.indexOf('ssss') + 4);
    var a_n = a.substring(a.indexOf('ssss') + 4, a.indexOf('.txt'));
    var b_s = b.substring(0, b.indexOf('ssss') + 4);
    var b_n = b.substring(b.indexOf('ssss') + 4, b.indexOf('.txt'));
    if (a_s < b_s)
        return -1;
    if (a_s > b_s)
        return1;
    returnparseInt(a_n) - parseInt(b_n);
});

jsFiddle

Solution 3:

Sort by numeric value within strings.

This assumes:

  • numbers are integers
  • every string is different
  • dates may be sorted as numbers (year,month,day)

["aa_123","aa_13","aa_2","aa_22_bb_23","aa_22_bb_3"].sort( function ( a , b ) {

varas = a.split(/([0-9]+)/); // splits string retaining separatorsvar bs = b.split(/([0-9]+)/);
    var i,c = Math.min(as.length,bs.length);
    for ( i=0;i<c && as[i]===bs[i];++i ) ;
    var an = (i&1)?+as[i]:as[i]; // separators (digits) always at odd indexvar bn = (i&1)?+bs[i]:bs[i];
    return (an<bn)?-1:1; // assumes every string different

} );

result:

[
  "aa_2",
  "aa_13",
  "aa_22_bb_3",
  "aa_22_bb_23",
  "aa_123"
]

Solution 4:

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.

functionweightedNumSort(myArray,weightNum,weightString) {    
    varWEIGHTS_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 NumbervarWEIGHT_STRING = weightString || 1; //And a weight for the string value. If none get passed, default weights are usedfunctionweightedSum (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 partvar 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 functionfor (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
}

Output

console.log (
   weightedNumSort (myArray)    
) /*
[
  "_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_ssss10.txt",
  "_aaaa_2013-09-25_ssss13.txt",
  "_aaaa_2013-09-26_ssss1.txt",
  "_aaaa_2013-09-26_ssss2.txt"
]*/

and a Fiddle

Post a Comment for "Sorting An Array Which Contains String, Date And Number"