Reputation: 748
I have an array of different dates.
Lets say
const arr = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec']
I want the dates in order, of the date closest to the date today. So in this case (18. marts), the output should be
const arr = ['21. may', '07. jun', '20. dec', '01. jan', '05. feb']
Is this even possible, when the year is not included?
Upvotes: 3
Views: 1134
Reputation: 13963
If you want to order the dates by distance to today with passed dates (negative distances) appearing last, you can do this:
const arr = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec'];
const today = new Date('2019/03/18'); // use new Date() for current day
arr.sort((a, b) => toDate(a) - toDate(b));
function toDate(str) {
const monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
const [day, monthName] = str.split(/\.\s*/);
const month = monthNames.indexOf(monthName.toLowerCase());
const date = new Date(today.getFullYear(), month, +day);
if (date < today) date.setFullYear(date.getFullYear() + 1);
return date;
}
console.log(arr); // ["21. may", "07. jun", "20. dec", "01. jan", "05. feb"]
Upvotes: 4
Reputation: 4010
If you add the string '2019'
onto the end of your date strings, JavaScript's Date constructor will parse it as being in this year. Once you have a bunch of Date objects, it's easy enough to sort your strings, and use findIndex to get the first one that is in the future:
const dates = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec'];
const sorted = [...dates].sort((a, b) => new Date(a) - new Date(b));
const soonest = sorted.findIndex(date => new Date(`${date} 2019`) > new Date());
const soonestDates = [...sorted.slice(soonest), ...sorted.slice(0, soonest)];
console.log(soonestDates); // ["21. may", "07. jun", "20. dec", "01. jan", "05. feb"]
Upvotes: 0
Reputation: 1073
If you are sure that there are no years in your dates data, you can try this:
function sortDateStrArrayFrom(dayAndMonth, array) {
const dateFrom = new Date(dayAndMonth);
const datesBefore = [];
const datesEqual = [];
const datesAfter = [];
array.forEach(dateStr => {
const date = new Date(dateStr);
if (date < dateFrom) {
datesBefore.push(dateStr);
}
if (date === dateFrom) {
datesEqual.push(dateStr);
}
if (date > dateFrom) {
datesAfter.push(dateStr);
}
})
return [...datesEqual, ...datesAfter, ...datesBefore];
}
const arr = ['21. may', '01. jan', '05. feb', '07. jun', '20. dec'];
sortDateStrArrayFrom('18. mar', arr); // ["21. may", "07. jun", "20. dec", "01. jan", "05. feb"]
If you need, it can be modified with date as input param or setting the same year for every date to work regardless of the year
Upvotes: 0