user1780370
user1780370

Reputation: 851

How to sort multidimensional array on datetime in jQuery

I am developing application where in jquery I have multidimensional array which I have to sort it but sort on datetime. Please refer below array which I have to sort.

array[["test1.jpg", "abc", "http://localhost7", "2015-09-20T16:23:18.000Z"], ["test2.jpg", "xyz", "http://localhost4", "2015-09-21T11:12:39.000Z"], ["test3.jpg", "pqr", "http://localhost6", "2015-09-20T23:08:42.000Z"]]

Any body have a experience and solutions in it.

Upvotes: 0

Views: 861

Answers (2)

bingjie2680
bingjie2680

Reputation: 7773

What about this:

array.sort(function (a, b) {
    if (a[3] > b[3]) return 1;
    if (a[3] < b[3]) return -1;
    return 0;
});

The result: http://jsbin.com/bakowowaku/edit?html,js,output

Upvotes: 2

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34199

You don't need jQuery to do this. You can do this using vanilla JS.

var arr = [["test1.jpg", "abc", "http://localhost7", "2015-09-20T16:23:18.000Z"], ["test2.jpg", "xyz", "http://localhost4", "2015-09-21T11:12:39.000Z"], ["test3.jpg", "pqr", "http://localhost6", "2015-09-20T23:08:42.000Z"]];

// Sorting function
arr.sort(function(a, b) {
    var dt1 = Date.parse(a[3]);
    var dt2 = Date.parse(b[3]);
    
    if (dt1 < dt2) return -1;
    if (dt2 < dt1) return 1;
    return 0;
});

// Output for example:
for (var i = 0; i < arr.length; i++)
{
    $("<p></p>").text(arr[i][3] + " - " + arr[i][0]).appendTo("body");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Related Questions