0

I have an array of 273 arrays with each array containing data about a regular season NFL football game. One of the data entries in the array is the date the game takes place on. I am trying to filter my array into sub arrays containing all the games in a particular week.

In other words I want to end up with 17 arrays each representing a week of the NFL season.

My arrays look like this ["2021-09-09", "DAL", "TB", ".55", .".45"].

I can use momentjs and write a function which checks if the date in an array is between two specified dates.

for(const element of data){
    if(moment(element[0]).isBetween("2021-09-08", "2021-09-14")){
        weekOneArray.push(element);
    }
 }

This works fine however I am going to have to hardcode an if statement for all 17 weeks of the season.

Can anyone think of a way to simplify my function so I can loop over weeks of the season?

13
  • Use moment().unix() to get the Unix timestamp which is a number. Then you can use it to sort the array. Commented Sep 24, 2021 at 19:04
  • No need to use Moment; just use element[0] > startDay && element[0] < endDay, and dates in yyyy-MM-dd format will sort naturally. Commented Sep 24, 2021 at 19:05
  • @HereticMonkey Won't I still need to hardcode my start and end date though? Commented Sep 24, 2021 at 19:15
  • Can't you generate all week dates for a season and then push your data based on these dates it. Commented Sep 24, 2021 at 19:17
  • 1
    moment(...).week() and lodash.groupBy() can make it clean & easier to understand Commented Sep 25, 2021 at 5:36

2 Answers 2

0

Last Update / Simplest solution with Lodash

With Lodash (as avinash mentioned) and moments it would be only:

const sortGamesAlt = (arrayOfGames) => {
  return groupBy(arrayOfGames, (game) =>
    moment(game[0]).isoWeekday(1)
  );
};

Updated

You can check this codesandbox and Adjust to your needs: https://codesandbox.io/s/crazy-mestorf-6yivl

After testing the previous code I noticed some details, it can work with this:

const sortGames = (arrayOfGames) => {
  const sortedGames = {};

  arrayOfGames.forEach((game) => {
    const startDate = moment(game[0]).isoWeekDay(1); // startOfWeek on Monday
    sortedGames[startDate] = sortedGames[startDate]
      ? [...sortedGames[startDate], game]
      : [game];
  });

  const sortedInfo = Object.entries(sortedGames).sort(
    (a, b) => new Date(a[0]) - new Date(b[0])
  );

  return sortedInfo;
};

Receiving:

 const arrayOfGames = [
    ["2021-09-09", "DAL", "TB", ".55", ".45"],
    ["2021-10-09", "X", "Y", ".55", ".45"],
    ["2021-11-09", "Z", "A", ".55", ".45"],
    ["2021-09-12", "B", "C", ".55", ".45"],
    ["2021-09-10", "D", "E", ".55", ".45"]
  ]; 

It'll return:

['Mon Nov 08 2021 00:00:00 GMT-0300', ['2021-11-09', 'Z', 'A', '.55', '.45']]
['Mon Oct 04 2021 00:00:00 GMT-0300', ['2021-10-09', 'X', 'Y', '.55', '.45']]
['Mon Sep 06 2021 01:00:00 GMT-0300', ['2021-09-09', 'DAL', 'TB', '.55', '.45'], ['2021-09-10', 'D', 'E', '.55', '.45'], '2021-09-12', 'B', 'C', '.55', '.45']]

OLD / Brief Idea

You can do something like this:

const arrayOfGames = [["2021-09-09", "DAL", "TB", ".55", ".45"], ["2021-10-09", "X", "Y", ".55", ".45"], ["2021-11-09", "Z", "A", ".55", ".45"], ["2021-09-12", "B", "C", ".55", ".45"]] // it'll have all your arrays: ["2021-09-09", "DAL", "TB", ".55", .".45"]
const sortedGames = {};

arrayOfGames.forEach(game => {
  // startOfWeek returns Sunday, so start on Monday if you add one day
  const startDate = moment(game[0]).startOf('week').add(1, 'days') 
  // endOfWeek returns Saturday, so finish on Sunday if you add one day
  const endDate = moment(game[0]).endOf('week').add(1, 'days')
  // Insert with the other games or JUST define new array only with this game
  sortedGames[startDate] = sortedGames[startDate] ? [...sortedGames[startDate], game] : [game]
})

Object
  // return an array of [startDateOfWeek, arrayOfGamesOfThatWeek]
  .entries(sortedGames)                             
  // sort the array based on the startDate
  .sort((a, b) => new Date(b[0]) - new Date(a[0]))  
  // Just return the array of games already sorted (you can also return the date if you want and ignore this line
  .map(a => a[1])                                   

// Returns [[["2021-11-09","Z","A",".55",".45"]],[["2021-10-09","X","Y",".55",".45"]],[["2021-09-12","B","C",".55",".45"]],[["2021-09-09","DAL","TB",".55",".45"]]]'
Sign up to request clarification or add additional context in comments.

Comments

0

You need to create a new Array with all weeks from your initial Array as your weeks are all in the same year you can use week number in year to determine them. This code will help you to find out the week number

currentdate = new Date();
var oneJan = new Date(currentdate.getFullYear(),0,1);
var numberOfDays = Math.floor((currentdate - oneJan) / (24 * 60 * 60 * 1000));
var result = Math.ceil(( currentdate.getDay() + 1 + numberOfDays) / 7);

After this you need to create another array which will be your final result with 17 weeks.

You need to loop your initial array and sort it to final array according to your array of weeknumbers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.