Skip to content
Advertisement

Get total sums for last 3, 7, 30 and 90 days with moment

I have an array of orders with created_at and total fields, where created_at is the date the order was created and total is what the user paid.

Now I want to get the sum of the totals for four different date intervals, last 3 days, 7 days, 30 days and 90 days, how can I use moment to check if an order is between these intervals and get the total sum for each interval.

const getIntervalsSum = (orders) =>
    {
       var threeDaysSum = 0;
       var sevenDaysSum = 0;
       var thirtyDaysSum = 0;
       var ninetyDaysSum = 0;
       
       for(var i=0; i<orders.length;i++)
       {
           //check interval with moment() here and add to respective sums
       }

    };

Advertisement

Answer

I think one generic function best suits this situation. Haven’t used moment before but based on the docs, this looks like it will work.

const totalOrders = (orders, daysAgo) => {
    let sum = 0;
    const then = moment().subtract(daysAgo, 'days');

    orders.forEach((order) => {
        if (moment(order.created_at).isAfter(then)) {
            sum += order.total;
        }
    });

    return sum;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement