Home > database >  How to filter this week from this month in javascript
How to filter this week from this month in javascript

Time:09-23

I have two functions one finds this week's files and the other one finds this month's files. I want to extract/filter this week's files from this month's files.

filterThisWeek(files) {
      const firstDayOfWeek = new Date(new Date().setDate(new Date().getDate() - new Date().getDay()));
      return this.filterToday(files).filter((f) => {
        return f.date >= firstDayOfWeek;
      });
    },
filterThisMonth(files) {
      const today = new Date();
      return files.filter((f) => {
        return (
          new Date(f.date).getMonth() === today.getMonth() &&
          new Date(f.date).getFullYear() === today.getFullYear()
        );
      });

using filterThisWeek function I want to extract this week's files from this month. So filterThisMonth function should find this month's files except this week's files. I want to do it in most efficient way but I dont know how to do it.

CodePudding user response:

I'd suggest creating functions getStartOfWeek() and getStartOfMonth() to establish the required date thresholds.

We'd then use these to create the desired limits in the filter functions filterThisWeek() and filterThisMonth().

filterThisWeek() should return any files with a date greater than or equal to the start of the week while filterThisMonth() should return any files with a date greater than or equal to the start of the month and less then the start of the week;

function getStartOfWeek(date) {
    const dt = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const offset = dt.getDate() - (dt.getDay() === 0 ? 6: dt.getDay() - 1);
    return new Date(dt.setDate(offset));
}

function getStartOfMonth(date) {
    return new Date(date.getFullYear(), date.getMonth(), 1)
}

function filterThisWeek(files, referenceDate = new Date()) {
    const lowerThreshold = getStartOfWeek(referenceDate);
    return files.filter(file => file.date >= lowerThreshold);
}

function filterThisMonth(files, referenceDate = new Date()) {
    const lowerThreshold = getStartOfMonth(referenceDate);
    const upperThreshold = getStartOfWeek(referenceDate);
    return files.filter(file => file.date >= lowerThreshold && file.date < upperThreshold);
}

function formatFile(file) {
    return `${file.date.toLocaleDateString('sv')}`;
}

const testFiles = Array.from( { length: 14 }, (v, k) => { 
    return { date: new Date(Date.now() - k*86400*1000)};
})

console.log('This weeks files:', filterThisWeek(testFiles).map(formatFile));
console.log('This months files:', filterThisMonth(testFiles).map(formatFile));
.as-console-wrapper { max-height: 100% !important; }

  • Related