Ranjith Varatharajan
Ranjith Varatharajan

Reputation: 1694

Issue in grouping by dates

I have a list of timers like

timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } 
timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } 
timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } 
timer 4 => { startDate = 18/01/2019 11PM, endDate = 19/01/2019 9AM }

I need to group by the dates with this logic.

  1. timer 1 starts at 17/01/2019 11PM and ends at next day. this timer should be grouped under 17/01/2019 (1 timer)
  2. timer 2 and timer 3 resides in the 18/01/2019, this should be grouped under 18/01/2019 (2 timers)
  3. timer 4 starts at 18 and ends at 19, which should be grouped under 19/01/201 (1 timer)

Code:

let sortedTimers = timers.sort((a, b) => {
     return a.startDate.isBefore(b.startDate) ? -1 : 1;
});        
let groupedByDate: { [date: string]: Timer[] } = _.groupBy(sortedTimers, timer => {
    let start = this.dateFormatter.toDayOfWeekLongDate(Timer.startDate);
    let end = this.dateFormatter.toDayOfWeekLongDate(Timer.endDate);
    return start == end? start:end; // wrong logic
});

This one returns only two groups 1. 18/01/2019 (3 timers) 2. 19/01/201 (1 timer) but I need three groups. I know the logic is wrong in the above code.

I'm using lodash for grouping. Any leads would be appreciated. Thanks.

Upvotes: 2

Views: 57

Answers (1)

N.Shrivastava
N.Shrivastava

Reputation: 94

You need to add current date in the condition as your logic takes into consideration the current date as well i.e. if(start == end) return start elseif(start < end & end==currDate) return start elseif(start < end & end>currDate) return end Something to that effect.

Upvotes: 2

Related Questions