-1

I have an array of objects which includes lastModifiedDate property in each object. I want to sort the array of objects according to lastModifiedDate property in ascending as well as descending order. If the dates are same then the sorting should be based on time of the date.

var completeData = [{name: 'xyz', lastModifiedDate: 1579329711458}, {name: 'abc', lastModifiedDate: 1579339014519}]

I have tried the below code to sort the above array.

For Ascending order:

completeData.sort(function(a, b){
   return new Date( a.lastModifiedDate ) < new Date( b.lastModifiedDate );
});

For Descending order:

completeData.sort(function(a, b){
    return new Date( a.lastModifiedDate ) > new Date( b.lastModifiedDate );
});
Tales
  • 169
  • 1
  • 9

3 Answers3

2

If lastModifiedDate is numberic value of timestamp then why need to compare date object of those timestamps you can compare those numbers only for efficient execution of sort as below.

completeData.sort(function(a, b){
   return  a.lastModifiedDate - b.lastModifiedDate;
});

When you need to display date formate you can use Date object for presentation purpose.

Haresh Vidja
  • 7,750
  • 3
  • 22
  • 40
  • 1
    @Tales please check jsfiddle https://jsfiddle.net/t3m2bcgL/ it is working correctly.. if you want in descending order then you have to use `return b.lastModifiedDate - a.lastModifiedDate;` – Haresh Vidja Jan 18 '20 at 11:09
  • Thanks you. Its working – Tales Jan 18 '20 at 11:44
1

For Descending ,

completeData.sort(function(a, b){
                var nameA= a.lastModifiedDate, nameB=b.lastModifiedDate
                if (nameA < nameB) 
                    return 1 
                if (nameA > nameB)
                    return -1
                return 0 //default return value (no sorting)
            });

For ascending ,

completeData.sort(function(a, b){
                    var nameA= a.lastModifiedDate, nameB=b.lastModifiedDate
                    if (nameA < nameB) 
                        return -1 
                    if (nameA > nameB)
                        return 1
                    return 0 //default return value (no sorting)
                });

This is for Date.

Pushprajsinh Chudasama
  • 2,445
  • 2
  • 8
  • 21
1
var completeData = [
  {
     name: 'xyz', 
     lastModifiedDate: 1579329711458
  },
  {
     name: 'abc', 
     lastModifiedDate: 1579339014519
  }
];
var result = completeData.sort(function (a, b) {
   return b.lastModifiedDate - a.lastModifiedDate;
})

console.log(result);