0

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 );
});
3
  • Both your code samples for ascending and descending sorting look the same. Commented Jan 18, 2020 at 10:50
  • I missed to change greater and less symbol Commented Jan 18, 2020 at 10:52
  • 1
    There's no need to transform lastModifiedDate into a Date. Commented Jan 18, 2020 at 10:53

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Tales please check jsfiddle jsfiddle.net/t3m2bcgL it is working correctly.. if you want in descending order then you have to use return b.lastModifiedDate - a.lastModifiedDate;
Thanks you. Its working
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.

3 Comments

The code is working. Thank you.
Can you please accept the answer . ? @Tales
I have accepted the above code as it was shorter
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.