JSFiddle - React, Tailwind, and code Playground
by neonDog
JavaScript
const test = [new Date('2021-09-12T12:30:31.862Z'),
new Date('2021-09-07T11:30:31.862Z'),
new Date('2021-09-11T04:30:31.862Z'),
new Date('2021-09-12T00:30:31.862Z'),
new Date('2021-09-12T01:30:31.862Z'),
new Date('2021-09-10T05:30:31.862Z')
];
function getNumberOfDays(date1, date2) {
// One day in milliseconds
const oneDay = 1000 * 60 * 60 * 24;
// Calculating the time difference between two dates
const diffInTime = date2.getTime() - date1.getTime();
// Calculating the no. of days between two dates
const diffInDays = Math.round(diffInTime / oneDay);
return diffInDays;
}
const today = new Date();
let scoreArr = [];
let eagernessFraction = 1;
//Assign a score
for (let i=0, l=test.length; i < l; i++) {
const score = i * eagernessFraction + getNumberOfDays(today, test[i]);
scoreArr.push([test[i], score]);
}
//Sort by score
scoreArr.sort((a, b) => {
return a[1] - b[1];
});
//Remove score, make flat array again
scoreArr = scoreArr.map(v => v[0]);
console.log(scoreArr);