简体   繁体   中英

Sorting String Date Array in ascending and Descending Order

Below piece of code:

var dateArr = new Array();
dateArr[0] = "11-12-2012";
dateArr[1] = "9-12-2014";
dateArr[2] = "11-12-2012";
dateArr[3] = "9-12-2011";

Have to sort the above String Date array in ascending and Descending Order. Please AnyOne give me some suggestions with examples for resolving the same. Thanks in Advance.

Try-

var arr = [];
for(var i =0; i<dateArr.length; i++)
{
    date1 = dateArr[i].split("-");
    if(date1[0]<10){date1[0]='0'+date1[0]} 
    if(date1[1]<10){date1[1]='0'+date1[1]} 
    arr.push(new Date(date1[2], date1[1] - 1, date1[0]));
}

arr.sort(function(a,b){return a-b});  //asc
console.log(formatDateArr(arr));

arr.sort(function(a,b){return b-a});  //desc
console.log(formatDateArr(arr));

function formatDateArr(arr)
{
    formatedArr = [];
    for(var i=0; i<arr.length; i++)
    {
        var curr_date = arr[i].getDate();
        var curr_month = arr[i].getMonth() + 1; //Months are zero based
        var curr_year = arr[i].getFullYear();
        formatedArr.push(curr_date + "-" + curr_month + "-" + curr_year);
    }
    return formatedArr;
} 

arr will be the sorted date array.

JSFiddle

This is untested code, but the answer would look like this:


dateArr.sort(function(d1,d2) {
    var year1 = d1.substr(6,4);
    var year2 = d2.substr(6,4);
    if (year1 < year2) return -1;
    if (year1 > year2) return 1;

    var month1 = d1.substr(3,2);
    var month2 = d2.substr(3,2);
    if (month1 < month2) return -1;
    if (month1 > month2) return 1;

    if (d1 < d2) return -1;
    if (d1 > d2) return 1;
    return 0;
});

I can't remember if the -1 or 1 means ascending or descending, so they might need to be swapped around.

Edit: Hang on, this won't work, because some of the dates don't have exactly 10 characters. So you'll have to do a character search (the "indexOf()" method) for the "-" characters, and use those indexes in the .substr method instead of a blind 6,4 or 3,2

One approach is to map the timestamps to dates then sort those:

 // Array of dates in d/m/y format let data = ['11-12-2012', '9-12-2014', '11-12-2012', '9-12-2011']; // Map strings to Date objects let dates = data.map(s => { let [d, m, y] = s.split(/\\D/); return new Date(y, m-1, d); }); // Sort dates.sort((a, b) => a - b); // Show sorted array dates.forEach(d => console.log(d.toDateString()))

Another approach is to map the strings to sortable timestamps, eg in ISO 8601 format:

 // Array of dates in d/m/y format let data = ['11-12-2012', '9-12-2014', '11-12-2012', '9-12-2011']; // Map strings to ISO 8601 format YYYY-MM-DD let dates = data.map(s => { let [d, m, y] = s.split(/\\D/); return `${y}-${m.padStart(2,'0')}-${d.padStart(2,'0')}`; }); // Sort - no special sort function required dates.sort(); // Show sorted array console.log(dates);

Format YYYYMMDD could also be used, but I think YYYY-MM-DD may be useful for other processes.

Lastly, if the intention is to just sort the original array, then the transformation can be undertaken in a sort function, but it's less efficient as each value may be transformed multiple times during the sort, eg

 // Array of dates in d/m/y format let data = ['11-12-2012', '9-12-2014', '11-12-2012', '9-12-2011']; // Use a sort function that sorts the original array data.sort((a, b) => { let p = s => { let [d, m, y] = s.split(/\\D/); return new Date(y, m-1, d); }; return p(a) - p(b); }); // Show sorted array console.log(data);

The same approach could also be taken using the reformatted string method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM