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"]]]'
element[0] > startDay && element[0] < endDay, and dates in yyyy-MM-dd format will sort naturally.moment(...).week()andlodash.groupBy()can make it clean & easier to understand