What I’m trying to do
So I have been trying to use the Obsidian Charts plugin to make a dataviewjs scrip for tracking things like the hours of sleep i get. I put this info in my daily note and want to use that info to make a line chart, i have watched a yt video for it and made a script that works, however it puts the data in the chart in order of creation of the file. So if i had a daily note from 29-11 and 28-11 the 29-11 would come in front of the 28-11, how do I fix this, so that the data is in ascending order of date?
I have the properties Hours_Sleep, Date and tags with #daily_note in the daily notes. This is the script i currently have:
// Define the date range
const startDate = new Date("2024-12-01"); // Start date (in YYYY-MM-DD for JavaScript)
const endDate = new Date("2024-12-31"); // End date
// Fetch and filter pages based on the date range
const pages = dv.pages('#daily_note and -"06 Templates"')
.filter(p => {
const dateMatch = p.file.name.match(/\d{2}-\d{2}-\d{4}/); // Match DD-MM-YYYY
if (!dateMatch) {
console.log(`File skipped (no valid date): ${p.file.name}`);
return false; // Skip files without valid dates
}
// Rearrange DD-MM-YYYY to YYYY-MM-DD for parsing
const [day, month, year] = dateMatch[0].split('-');
const pageDate = new Date(`${year}-${month}-${day}`);
console.log(`Parsed date for file: ${p.file.name} -> ${pageDate}`);
return pageDate >= startDate && pageDate <= endDate; // Check range
})
.sort(p => {
const dateMatch = p.file.name.match(/\d{2}-\d{2}-\d{4}/);
const [day, month, year] = dateMatch[0].split('-');
return new Date(`${year}-${month}-${day}`); // Sort by rearranged date
});
// Extract the dates and Hours_Sleep values from the filtered pages
const rawDates = pages.map(p => p.file.name.match(/\d{2}-\d{2}-\d{4}/)?.[0]); // Extract raw date strings
const dates = rawDates; // Keep as DD-MM-YYYY since it matches the file name format
const Hours_Sleep = pages.map(p => p.Hours_Sleep).values;
// Ensure there's data to display
if (dates.length === 0 || Hours_Sleep.length === 0) {
dv.span("No valid data found for the selected date range.");
} else {
// Prepare the chart data
const chartData = {
type: 'line',
data: {
labels: dates, // Use DD-MM-YYYY directly for labels
datasets: [{
label: 'Hours of Sleep',
data: Hours_Sleep,
backgroundColor: 'rgba(0, 123, 255, 1)', // Blue for sleep
borderColor: 'rgba(0, 123, 255, 0.8)',
borderWidth: 1,
}]
}
};
// Render the chart
window.renderChart(chartData, this.container);
}
Things I have tried
I have tried using chatgpt, but that gives even more erros everytime it comes up with an ‘answer’. Help would be appreciated, as I don’t have a lot of knowledge about this:)