locked
Sorting WinJS.Binding.List containing dates

    Question

  • Hi All,

    I have a list something like this

     var myList = new WinJS.Binding.List([
            { name: "aaaa", date: "12 Dec 2012" },
            { name: "bbbb", date: "9 Feb 2013"},
            { name: "ccccc", date: "6 Sep 2012"},
            { name: "dddd", date: "21 Jun 2013"},
    
        ]);
    
    

    Users will have the option to sort the data binded to the listview using dropdown

    So how to sort this list ?

    I have checked http://msdn.microsoft.com/en-us/library/windows/apps/hh700742.aspx but there they are sorting based on the first char.

    Can anyone suggest how to sort  a List based on dates???

    Thanks in advance.


    Nazia

    Monday, November 04, 2013 11:59 AM

Answers

  • Hi!

    Here is an example on how to sort dates:

    var data = new WinJS.Binding.List([
        { name: "aaaa", date: "12 Dec 2012" },
        { name: "bbbb", date: "9 Feb 2013" },
        { name: "ccccc", date: "6 Sep 2012" },
        { name: "dddd", date: "21 Jun 2013" }
    ]);
    
    // Here is an example on how to sort dates in
    // an ascending order.
    data = data.createSorted(function (left, right) {
        // 'left' and 'right' are items from your list:
        // e.g.: { name: "ccccc", date: "6 Sep 2012" }
    
        // .getTime() will return the amout of milliseconds that
        // have passed from 01.01.1970 and to the specified date.
        left = new Date(left.date).getTime();
        right = new Date(right.date).getTime();
    
        // The sorter function must return one of the following numeric values:
        // negative if the first argument is less than the second, 
        // positive if the first argument is greater than the second,
        // zero if the two arguments are equivalent.
    
        if (left < right)
            return -1;
                    
        if (left > right)
            return 1;
    
        return 0;
    });

    Documentation:
    List.createSorted method
    Date.getTime() method

    • Proposed as answer by Aratys Monday, November 04, 2013 2:24 PM
    • Marked as answer by Nazia Firdouse Tuesday, November 05, 2013 6:46 AM
    Monday, November 04, 2013 1:55 PM