3

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?

TJ Weems
  • 1,086
  • 3
  • 21
  • 37

2 Answers2

12

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)
danh
  • 62,181
  • 10
  • 95
  • 136
  • 2
    Thanks! this is what I was looking for. My actual code is stringing on multiple sorting parameters so It took me a second to modify it to what I needed but it works. – TJ Weems Mar 28 '20 at 22:31
-1

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 filter function should test `date[firstSort] != null`. Also, the OP wants the objects with the null due_date sorted to the end, not removed, so this answer would need to grab those first with another (opposite) filter, then concat them back on after the sort. – danh Mar 28 '20 at 22:29
  • as @danh said, I still want the null value to remain after sorting, but thanks for the help. – TJ Weems Mar 28 '20 at 22:32
  • Sorry forgot the date[firstSort] and I excluded because in your last like you said "How can I compare a null date or exclude it when sorting?" – Fried noodles Mar 28 '20 at 22:43