Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of dates to nearest date

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?

like image 281
jonask Avatar asked Mar 02 '26 07:03

jonask


1 Answers

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"]
like image 200
jo_va Avatar answered Mar 03 '26 21:03

jo_va



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!