filter array of objects on click by 'last month' and 'last week' using moment.js

Varsha picture Varsha · Jan 27, 2016 · Viewed 9.4k times · Source

I have a dateCreated as 2015-12-11T11:12:14.635Z coming from database for every object in an array

I want to filter that array for the last week and last month

Problem is if today is the 19th March, i was to search from the 11th to the 18th for the last 7 days and that seems to search for the last 7 days by calculating 24 hours * 7 by my searches need to start from 00:00:01 each day.

now i 1st want to calculate last week first.. based on current date using moment.js and then i will convert it to the above format so that i can filter data

Basically, I want to calculate last week based on current timestamp.

Answer

vinjenzo picture vinjenzo · Jan 27, 2016

the dates should be:

var last7DayStart = moment().startOf('day').subtract(1,'week');
var lastMonthThisDay = moment().startOf('day').subtract(1,'month');
var yesterdayEndOfRange =  moment().endOf('day').subtract(1,'day');

then if it is a javascript filter i would use lodash and do:

var javascriptArrayOfObjectsWithDates = [
          { date : '2015-12-11T11:12:14.635Z', anotherProperty: 0 },
          { date : moment().subtract(1, 'day' ).format(), testThis: 'works!'}
        ];

var filteredObjects = _.filter(javascriptArrayOfObjectsWithDates,     
                       function(each){ 
                          return moment(each.date)
                            .isBetween(last7DayStart, yesterdayEndOfRange) ;
                       });