'JavaScript sort date according to week and month to sum up the amount

I am trying to sort the profit for this week, last week, this month and last month from an array. The sameple data:

var arr = [{date: '2017/12/16',  profit: 12.50},
{date: '2017/05/01', profit: 13.50},
{date: '2017/04/20', profit: 14.50},
{date: '2017/03/10', profit: 15.50},
{date: '2017/08/15', profit: 16.50},
{date: '2017/08/16', profit: 26.50},
{date: '2017/08/24', profit: 16.50},
{date: '2017/08/25', profit: 36.50},
{date: '2017/03/06', profit: 17.50},
{date: '2017/02/04', profit: 18.50},
{date: '2017/01/07', profit: 19.50}];

I wanted to sort and get the profit according to this week/last week/this month/last month. I have tried with getting today and yesterday's profit with this:

var today = getTodayDate();
var todayProfit = 0;

for(var i = 0; i < arr.length; i++){
if(arr[i].date == today){
    todayProfit = arr[i].total;
    break;
}
}

Same goes for yesterday which I basically get the yesterday's date. How can I actually sort for this week/last week/this month/last month? Do I have to create another array to get all the dates and do nested for loop?

Is there any better approach?

Desired output:

This week profit: 53.00
Last week profit: 43.00
This month profit: 96.00
Last month profit: 0.00


Solution 1:[1]

You dont need to sort. You just need to check for current day, yesterday, or this month, and sum up the values when iterating:

 const today = "2017/08/26", yesterday = " 2017/08/25";
 const month = today.substr(0,-3);

 //results
 let profit = {
  today:0,
  yesterday:0,
  month:0
 };

arr.forEach(({date,profit}) =>{
 if(date === today) profit.today += profit;
 if(date === yesterday) profit.yesterday += profit;
 if(date.substr(0,-3) === month) profit.month += profit;
});

console.log( profit );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonas Wilms