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
2 Answers
Reset to default 18Transform 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 :)