Ad
Dates/Time
Data Types

Sort By Week

Given the random number of dates, sort them in a chronological way.

Result should be returned as an array.

Code
Diff
  • function groupByWeek(days) {
      const dates = days.map(a => new Date(a)).sort((a, b) => b - a);
      
      console.log(dates.map(a => (a.getMonth()+1) + "/" + a.getDate() + "/" + a.getFullYear()))
    
      let currentMonday = new Date();
      currentMonday.setDate(dates[0].getDate() - dates[0].getDay())
      
      let currentSunday = new Date()
      currentSunday.setDate(currentMonday.getDate() + 6);
      
      //console.log(firstMonday.getDay())
      //console.log(firstSunday.getDay())
      
      let weeks = []
      let currentWeek = []
      for(let date of dates) {
        if(date >= currentMonday && date <= currentSunday) {
          currentWeek.push((date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear())
        } else {
          if(currentWeek.length > 0) {
            weeks.push(currentWeek)
          }
          currentWeek = [(date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear()]
          currentMonday.setDate(date.getDate() - date.getDay())
          currentSunday.setDate(currentMonday.getDate() + 6);
        }
        
      }
      if(currentWeek.length > 0) {
        weeks.push(currentWeek)
      }
      
      return weeks;
      
    }
    • function groupByWeek(days) {
    • var dates = days.map(a => new Date(a)).sort((a, b) => b - a);
    • const dates = days.map(a => new Date(a)).sort((a, b) => b - a);
    • console.log(dates.map(a => (a.getMonth()+1) + "/" + a.getDate() + "/" + a.getFullYear()))
    • var currentMonday = new Date();
    • let currentMonday = new Date();
    • currentMonday.setDate(dates[0].getDate() - dates[0].getDay())
    • var currentSunday = new Date()
    • let currentSunday = new Date()
    • currentSunday.setDate(currentMonday.getDate() + 6);
    • //console.log(firstMonday.getDay())
    • //console.log(firstSunday.getDay())
    • var weeks = []
    • var currentWeek = []
    • for(var date of dates) {
    • let weeks = []
    • let currentWeek = []
    • for(let date of dates) {
    • if(date >= currentMonday && date <= currentSunday) {
    • currentWeek.push((date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear())
    • } else {
    • if(currentWeek.length > 0) {
    • weeks.push(currentWeek)
    • }
    • currentWeek = [(date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear()]
    • currentMonday.setDate(date.getDate() - date.getDay())
    • currentSunday.setDate(currentMonday.getDate() + 6);
    • }
    • }
    • if(currentWeek.length > 0) {
    • weeks.push(currentWeek)
    • }
    • return weeks
    • return weeks;
    • }