I'm developing an algorithm to create a list of dates, and i need in every monday of week the code break to another array. But I don't know how to do that.
PS: Even though the monday not exists in original array, i want do create another array, for the next dates.
const mealsRooms = await prisma.users.findUnique({
where: {
id: req.params.userId
},
select: {
MealsRooms: {
select: {
id: true,
servingSabado: true,
servingDomingo: true
}
}
}
});
const monthFull = req.params.month.split(".");
const month = monthFull[0];
const year = monthFull[1];
const totalDays = new Date(parseInt(year), parseInt(month), 0).getDate();
let semana = [];
for(let i = 1; i <= totalDays; i++){
const data = new Date(year + "-" + (parseInt(month)+1).toString() + "-" + i);
const indexMealZone = mealsRooms.MealsRooms.findIndex((room) => { return (room.id === req.params.zonaConsumo); })
if(mealsRooms.MealsRooms[indexMealZone].servingSabado && data.getDay() === 6){
semana.push({
date: data.toDateString(),
price: 1.46,
status: 0,
type: "NB",
cosumZone: "NB"
});
}else if(mealsRooms.MealsRooms[indexMealZone].servingDomingo && data.getDay() === 0){
semana.push({
date: data.toDateString(),
price: 1.46,
status: 0,
type: "NB",
cosumZone: "NB"
});
}
if(data.getDay() !== 6 && data.getDay() !== 0){
semana.push({
date: data.toDateString(),
price: 1.46,
status: 0,
type: "NB",
cosumZone: "NB"
});
}
}
res.status(200).json({
listRefeicoes: [semana]
});
Original Array
{"listRefeicoes":[[
{"date":"Thu Sep 01 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 02 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 05 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 06 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 07 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 08 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 09 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 12 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 13 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 14 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 15 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 16 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 19 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 20 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 21 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 22 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 23 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Mon Sep 26 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Tue Sep 27 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Wed Sep 28 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Thu Sep 29 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"},
{"date":"Fri Sep 30 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}
]]}
Final Array
{"listRefeicoes":[[Week 1], [Week2], ...]}
I tried to separate by weeks but this creates the problem that if the second one doesn't exist in the week it doesn't create the new array.
We can fold our list down into a nested list by keeping track of when our day of the week decreases. We do that by scanning the date property for any of "Mon", "Tue", "Wed", etc, keeping track of the index where that matched. If it's smaller than our current entry, we start a new array. If not, we append to the existing one. Here's one way to do this:
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
const splitWeeks = (os) => os .reduce (
({curr, weeks}, o) => {
const next = days .findIndex (dow => o .date .includes (dow))
return next < curr
? {curr: 0, weeks: weeks .concat ([[o]])}
: {curr: next, weeks: [...weeks .slice (0, -1), weeks .at (-1) .concat (o)]}
},
{curr: Infinity, weeks : []}
) .weeks
const update = ({listRefeicoes, ...rest}) => ({
listRefeicoes: splitWeeks (listRefeicoes [0]),
...rest
})
const input = {"listRefeicoes":[[{"date":"Thu Sep 01 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 02 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 05 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 06 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 07 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 08 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 09 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 12 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 13 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 14 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 15 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 16 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 19 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 20 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 21 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 22 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 23 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Mon Sep 26 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Tue Sep 27 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Wed Sep 28 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Thu Sep 29 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}, {"date":"Fri Sep 30 2022","price":1.46,"status":0,"type":"NB","cosumZone":"NB"}]]}
console .log (update (input))
.as-console-wrapper {max-height: 100% !important; top: 0}
I need to get my data ordered by date and events but I'm struggling to get it working using AlaSQL query on Date objects:
function testOrderBy() {
var data = [{event:'A', date: new Date('2021-04-21')},
{event:'B', date: new Date('2021-04-21')},
{event:'C', date: new Date('2021-04-21')},
{event:'D', date: new Date('2021-04-20')}];
console.log(data);
var res = alasql(`SELECT event, date FROM ? ORDER BY date, event`, [data]);
console.log(res);
}
And the result obtained is:
[ { event: 'D',
date: Tue Apr 20 2021 02:00:00 GMT+0200 (Central European Summer Time) },
{ event: 'C',
date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
{ event: 'B',
date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
{ event: 'A',
date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) } ]
I was expecting:
[ { event: 'D',
date: Tue Apr 20 2021 02:00:00 GMT+0200 (Central European Summer Time) },
{ event: 'A',
date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
{ event: 'B',
date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
{ event: 'C',
date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) } ]
The problem does not occur if dates are not Date objects but ISO strings:
function testOrderBy() {
var data = [{event:'A', date: '2021-04-21'},
{event:'B', date: '2021-04-21'},
{event:'C', date: '2021-04-21'},
{event:'D', date: '2021-04-20'}];
console.log(data);
var res = alasql(`SELECT event, date FROM ? ORDER BY date, event`, [data]);
console.log(res);
}
The result is as expected D, A, B, C
Any idea ?
It is necessary to create the table schema to correctly consider the column as a Date type, as follows:
alasql("CREATE TABLE events (event string, date date)");
alasql.tables.events.data = [{event:'A', date: new Date('2021-04-21')},
{event:'B', date: new Date('2021-04-21')},
{event:'C', date: new Date('2021-04-21')},
{event:'D', date: new Date('2021-04-20')}];
alasql(`SELECT event, date INTO HTML("#res") FROM events ORDER BY date, event`);
<script src="https://cdn.jsdelivr.net/npm/alasql#1.7.3/dist/alasql.min.js"></script>
<div id="res">
</div>
I have a simple helper function to find date in the array of dates based on given day, in this function I convert day name to day number, and then I want to find all dates with the given day number:
function findDatesByWeekday(date, weekdayArr) {
const dayNumbers = weekdayArr.map(({ day }) => textToDayNumber(day));
return dayNumbers.find(n => {
console.log(
`n: ${n}, getDay: ${new Date(date).getDay()} result: ${new Date(
date
).getDay() === n} date: ${date}`
);
return new Date(date).getDay() === n;
});
}
However, it does not find Sundays, although the result of return statement is true.
n: 6, getDay: 6 result: true date: Sat Oct 16 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 0 result: false date: Sun Oct 17 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 0, getDay: 0 result: true date: Sun Oct 17 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 6 result: true date: Sat Oct 23 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 0 result: false date: Sun Oct 24 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 0, getDay: 0 result: true date: Sun Oct 24 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 6 result: true date: Sat Oct 30 2021 12:00:00 GMT+0200 (Central European Summer Time)
n: 6, getDay: 0 result: false date: Sun Oct 31 2021 12:00:00 GMT+0100 (Central European Standard Time)
n: 0, getDay: 0 result: true date: Sun Oct 31 2021 12:00:00 GMT+0100 (Central European Standard Time)
What is more, it generated unwanted output as I was asking for five dates, and it returned five Saturdays instead of three Saturdays and two Sundays.
0: Sat Oct 16 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
1: Sat Oct 23 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
2: Sat Oct 30 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
3: Sat Nov 06 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
4: Sat Nov 13 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
With every other week day it works just fine, it's just the Sunday, so I am quite sure that it comes down to zero being a falsy value, and I know how to fix it function below works as intended
function findDatesByWeekday(date, weekdayArr) {
const dayNumbers = weekdayArr.map(({ day }) => textToDayNumber(day));
return dayNumbers.includes(new Date(date).getDay());
}
I just want to understand why :)
Thanks
Hi is a start of the edit of the question as you have requested. You are right, I am sorry I should have included the context by default. I do not use filter as I use this helper in the filter method as a predicate
newHighlightedDays = benchmark.filter(date =>
findDatesByWeekday(date, weekDaysWithTime))
.filter((_, i) => i < lessonCount);
weekdaysWithTime is an array of objects like these:
{
day: "Piątek",
time: {h: 12, m: 30}
},
{
day: "Sobota",
time: {h: 12, m: 30}
},
{
day: "Niedziela",
time: {h: 12, m: 30}
}
and textToDayNumber is this function:
export function textToDayNumber(text) {
switch (text.toLowerCase()) {
case "niedziela":
return 0;
case "poniedziałek":
return 1;
case "wtorek":
return 2;
case "środa":
return 3;
case "czwartek":
return 4;
case "piątek":
return 5;
case "sobota":
return 6;
default:
throw new Error("invalid day name");
}
}
I am sure that this is not a timezone issue as it compares not dates per se, but a weekday name parsed to day number with the date from react-day-picker, here is an example of benchmark array to reproduce the code:
Tue Oct 19 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Wed Oct 20 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Thu Oct 21 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Fri Oct 22 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sat Oct 23 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sun Oct 24 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Mon Oct 25 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Tue Oct 26 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Wed Oct 27 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Thu Oct 28 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Fri Oct 29 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sat Oct 30 2021 12:00:00 GMT+0200 (Central European Summer Time) {}
Sun Oct 31 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Mon Nov 01 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Tue Nov 02 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Wed Nov 03 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Thu Nov 04 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Fri Nov 05 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sat Nov 06 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sun Nov 07 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Mon Nov 08 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Tue Nov 09 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Wed Nov 10 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Thu Nov 11 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Fri Nov 12 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sat Nov 13 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Sun Nov 14 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Mon Nov 15 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Tue Nov 16 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Wed Nov 17 2021 12:00:00 GMT+0100 (Central European Standard Time) {}
Thank you! :)
Not sure I understood the question:
and then I want to find all dates with the given day number:
find returns only the first matching item. Use filter to return an array of matching items.
function findDatesByWeekday(date, weekdayArr) {
const dayNumbers = weekdayArr.map(({ day }) => textToDayNumber(day));
return dayNumbers.filter(n => {
console.log(
`n: ${n}, getDay: ${new Date(date).getDay()} result: ${new Date(
date
).getDay() === n} date: ${date}`
);
return new Date(date).getDay() === n;
});
}
I have a JSON js object which I am getting using AJAX.
the problem is I don't have much control on the backend, so the data is coming in simple JS object.
I have a JSON file as follows
var test =
[
{value : 23,
file_date : Wed Jan 01 2014 05:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 01 2014 09:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 01 2014 02:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 02 2014 06:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 02 2014 09:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 02 2014 04:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 03 2014 02:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 03 2014 01:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 03 2014 10:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 04 2014 7:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 05 2014 10:34:53 GMT+0530 (IST)
},
{value : 23,
file_date : Wed Jan 06 2014 11:34:53 GMT+0530 (IST)
}
]
the file_ts has different timestamp. my problem is that I have to consolidate this data.
If user select 1 Day then I have to get sum of all data hour wise. If there are 4 values between 2 and 3 hr then I have to sum that data hour wise.
then if weekly then weekly. I am trying to write a nodejs server with express and mysql but its also not working from there.
Here is what, i'm assuming, you were asking for:
If a user selects 'January 1st', you want to grab all info where
file_date is on the selected date and add up all the hours.
Here are the steps you would need to take:
Get data from Ajax Call
Search data by Date (input) and add matches together
Convert matches to date and add up hours
NOTE: I've converted your timezone (IST) to (UTC) so the output will be in GMT
// Test data
var test = [{
value: 23,
file_date: "Wed Jan 01 2014 05:34:53 GMT+0530 (IST)"
},{
value: 23,
file_date: "Wed Jan 01 2014 09:34:53 GMT+0530 (IST)"
},{
value: 23,
file_date: "Wed Jan 01 2014 02:34:53 GMT+0530 (IST)"
},{
value: 23,
file_date: "Thu Jan 02 2014 06:34:53 GMT+0530 (IST)"
},{
value: 23,
file_date: "Thu Jan 02 2014 09:34:53 GMT+0530 (IST)"
},{
value: 23,
file_date: "Thu Jan 02 2014 04:34:53 GMT+0530 (IST)"
}
];
var userInput = 1; // This is the date they typed in
// This function returns all records for a specific day (integer)
var getAllDayData = function(day){
var response = [];
for(var i=0;i<test.length;i++){
var fileDate = new Date(test[i].file_date);
if(fileDate.getDate() === day){ // getDate gets you day of month
response.push(fileDate);
}
}
return response;
};
var getTotalHoursFromDates = function(data){
var totalHours = 0;
for(var i=0;i<data.length;i++){
totalHours += data[i].getHours();
}
return totalHours;
};
var getTotalHoursFromInput = function(day){
var dayData = getAllDayData(day);
var response = getTotalHoursFromDates(dayData);
return response;
};
// Call the function
var dayTotal = getTotalHoursFromInput(userInput);
console.log(dayTotal); // 58
Regarding your request to grab weekly hours: You will have to add a function that takes all the days of the week (input), gather all the information for each day, add then add all of those hours together. This is a continuation of the code above.
var week = [31,1,2,3,4,5,6]; // This is the days of the selected full week
var getAllWeekData = function(days){
var response = [];
for(var i=0;i<days.length;i++){
var day = getAllDayData(days[i]);
if(day[0] != null) { // Checks for undefined or null
for(var y=0;y<day.length;y++){
response.push(day[i]);
}
}
}
return response;
};
var getAllWeekDays = function(selectedDays){
var allDays = getAllWeekData(selectedDays);
var response = getTotalHoursFromDates(allDays);
return response;
};
var weekTotal = getAllWeekDays(week);
console.log(weekTotal); // 120