简体   繁体   中英

How to sort array by date when some dates are null

So I am trying to sort array of objects by date but I want objects with dates to be priority over objects with null dates.

Example of non sorted array:

[
  {due_date: null},
  {due_date: '03/11/2020'},
  {due_date: '02/10/2020'}
]

And I would like the the array to be in this order once sorted

[
  {due_date: '02/10/2020'},
  {due_date: '03/11/2020'},
  {due_date: null}
]

However when I run the array through my script

var firstSort = 'due_date'

return array.sort((a, b) => {
  return new Date(a[this.firstSort]) - new Date(b[this.firstSort])
})

I get this result

[
  {due_date: null},
  {due_date: '02/10/2020'},
  {due_date: '03/11/2020'}
]

How can I compare a null date or exclude it when sorting?

Transform the strings to dates and sort. For the nulls, use date in the distant future so they will sort to the end.

 let dates = [ { due_date: null }, { due_date: '03/11/2020' }, { due_date: '02/10/2020' } ] const distantFuture = new Date(8640000000000000) const firstSort = 'due_date' let sorted = dates.sort((a, b) => { let dateA = a[firstSort] ? new Date(a[firstSort]) : distantFuture let dateB = b[firstSort] ? new Date(b[firstSort]) : distantFuture return dateA.getTime() - dateB.getTime() }) console.log(sorted)

All you have to do is, if indeed excluding is your goal, you filter the array first for all non-null values and then you sort them like so:

var firstSort = 'due_date'

let dates = [
{ due_date: "01/10/2019" },
{ due_date: "10/11/2019" },
{ due_date: "05/09/2019" },
{ due_date: null },
{ due_date: "01/01/2020" },
{ due_date: null },
]

dates.filter(date => date[firstSort] !== null).sort((a, b) => new Date(a[firstSort]) - new Date(b[firstSort]))

That should do the trick :)

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