Hi there !
I am trying to build a function to generate dataset.
function createDatasets(data, chartLabels, dataLabels, dataValues, chartColors = ['rgba(75, 192, 192, 0.5)', 'rgba(255, 99, 132, 0.5)', 'rgba(54, 162, 235, 0.5)', 'rgba(255, 206, 86, 0.5)', 'rgba(153, 102, 255, 0.5)']) {
// Get all unique values from the chartLabels (e.g., all unique months)
const allLabels = [...new Set(data.map(item => item[chartLabels]))];
// Initialize a map to store the total amounts for each unique data label, defaulting to zero
const dataMap = {};
// Iterate through the data and dynamically create maps for each unique value in dataLabels
data.forEach(item => {
const labelValue = item[dataLabels];
const chartLabel = item[chartLabels];
const value = item[dataValues];
// Initialize the map for the label if not already present
if (!dataMap[labelValue]) {
dataMap[labelValue] = new Map(allLabels.map(label => [label, 0]));
}
// Update the value for the chart label
const currentAmount = dataMap[labelValue].get(chartLabel) || 0;
dataMap[labelValue].set(chartLabel, currentAmount + Math.abs(value));
});
// Convert the maps into dataset objects
const datasets = Object.keys(dataMap).map((labelValue, index) => {
return {
label: labelValue,
backgroundColor: chartColors[index % chartColors.length], // Assign color from chartColors array
data: allLabels.map(label => dataMap[labelValue].get(label) || 0) // Use allLabels to ensure order and handle missing labels
};
});
// Return an array of datasets for Chart.js
return datasets;
}
I works when I use it directly in the dataset for chart but I tryed to use it like that :
const data = collections['c095b348-c578-4a41-8611-e19e8ec1e93b'].data;
const chartLabels = 'year_month'; // Specify the chartLabels (e.g., month or year-month)
const dataLabels = 'profit_or_loss'; // Specify the dataLabels (e.g., profit or loss)
const dataValues = 'total_amount'; // Specify the dataValues (e.g., amount to sum)
const chartColors = ['rgba(75, 192, 192, 0.5)', 'rgba(255, 99, 132, 0.5)', 'rgba(54, 162, 235, 0.5)', 'rgba(255, 206, 86, 0.5)', 'rgba(153, 102, 255, 0.5)'];
return formulas['11036945-0a27-4d3d-bebf-58b8ddbcae84'](data, chartLabels, dataLabels, dataValues, chartColors)
My goal is to have just one project function to generate the datasets. I have done this with GPT as I am not a dev, any clue of what I am not doing right ?