最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to sort array by date when some dates are null - Stack Overflow

programmeradmin9浏览0评论

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 pare a null date or exclude it when sorting?

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 pare a null date or exclude it when sorting?

Share Improve this question asked Mar 28, 2020 at 21:49 TJ WeemsTJ Weems 1,1143 gold badges22 silver badges39 bronze badges 2
  • dateA == null ? sortrulevalue : dateA - dateB – Estradiaz Commented Mar 28, 2020 at 21:54
  • sort an array so that null values always e last – awran5 Commented Mar 28, 2020 at 22:02
Add a ment  | 

2 Answers 2

Reset to default 18

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 :)

发布评论

评论列表(0)

  1. 暂无评论