Reputation: 3
I have an array of objects for a project in which they work kind of like entries to a blog. I'm then attempting to sort the entries by the publication date of each entry (recents first), however, apparently the sorting function isn't considering the year value or maybe some other issue I'm missing.
One of the entries was published the 23 of June (6) in 2019 and it is the first value of the output array because it's the entry with the most recent date. BUT if I try to change its year to something like 2005, it will stay at the top like if the function would be ignoring the year. I also tried changing it into 0 but the result remained the same.
For the date I used another array in which index 0 refers to the Day, index 1 to the Month and index 2 to the Year.
[{Id: "P3", Date: [23, 6, 2019]}, ...]
I use the three values of the Date arrays to calculate the total number of days since day 0 and compare them (the biggest number of days = the most recent entry)
array.sort((a, b) => ((a.Date[0] + (a.Date[1] * 30) + (a.Date[2] * 365)) < (b.Date[0] + (b.Date[1] * 30) + (b.Date[2] * 365)) ? 1 : -1)).map(item => item.Id)
The function outputs an array with the Ids of the entries they refer to, supposedly, in order.
Any help fixing my code will be helpful and appreciated :)
Upvotes: 0
Views: 567
Reputation: 55333
Try this.
function convertDateToNumber(date) {
return Number(date[2] + date[1].toString().padStart(2, 0) + date[0].toString().padStart(2, 0));
}
var dates = [
{ Id: "P3", Date: [23, 6, 2019] },
{ Id: "P4", Date: [3, 6, 2019] },
{ Id: "P5", Date: [23, 12, 2019] },
{ Id: "P6", Date: [23, 7, 2019] },
{ Id: "P7", Date: [3, 12, 2019] }
];
dates.sort((a, b) => {
var aNumber = convertDateToNumber(a.Date);
var bNumber = convertDateToNumber(b.Date);
if (aNumber < bNumber) {
return -1;
}
if (aNumber > bNumber) {
return 1;
}
return 0;
});
console.log(dates);
Upvotes: 1
Reputation: 318
You'd better use Date library
to compare Date data, for example: moment.js.
Upvotes: 0
Reputation: 11
Use JavaScript data type 'Date' instead of array format. Then compare the dates to sort.
Change your code
[{Id: "P3", Date: [23, 6, 2019]}, ...]
to
[{Id: "P3", date: '23/6/2019'/*use proper date format*/}, ...]
With this change, you can sort the objects as below
array.sort(function(a,b){
var date1 = new Date(a.date);
var date2 = new Date(b.date);
return date1 > date2? 1:-1;
});
Upvotes: 0