Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

327
Visualizações
Average 2 Keys in ChartJS

I'm working with ChartJS on a project the moment, showing user-added records for tracking weight, heart rate etc. I am running into a exception where if the user adds 2 records for 1 day that are slightly different values, I am getting this:

enter image description here

Where you can see it has added them both to the same axis. An example of the data set is below:

[    
  {x: '2021-09-21', y: '30.00'},
  {x: '2021-09-22', y: '65.00'},
  {x: '2021-09-23', y: '48.00'},
  {x: '2021-09-23', y: '25.00'},
  {x: '2021-09-24', y: '55.00'},
]

Is there something inbuilt with ChartJS that would average these out or is it a case of implementing it myself as I load the data in?

Thank you

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So I thought it would be easier just to reduce the array down myself and provide that as the dataset for ChartJS, i'll leave the code below for anyone in a similar position. It makes use of a React hook to update whenever the actual dataset is updated:

/**
 * When the metric values have been updated
 */
useEffect(() => {
    /**
     * Init a new object to store the values in
     */
    let sorted = {};
    /**
     * Loop through all the metric values that were added
     */
    metricValues.forEach((value) => {
        /**
         * If we already have a copy of it in the new object
         */
        if (sorted[`${value.x}`]) {
            /**
             * Push the value onto the array
             */
            sorted[`${value.x}`] = [...sorted[`${value.x}`], value.y];
        } else {
            /**
             * Otherwise just set it as the first value
             */
            sorted[`${value.x}`] = [value.y];
        }
    });
    /**
     * Init a new array to hold the reduced data
     */
    let reducedData = [];
    /**
     * Loop through each of the now sorted values
     */
    Object.entries(sorted).forEach((dataPoint) => {
        /**
         * Get the records array, holding the values to be averaged
         */
        const dateRecords = dataPoint[1];
        /**
         * Make a sum of all the records
         */
        const recordsSum = dateRecords.reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
        /**
         * Then find the avaerage
         */
        const recordsAvg = parseFloat(recordsSum / dateRecords.length).toFixed(2);
        /**
         * Push this new reduced version of the metric records to our local array
         */
        reducedData = [...reducedData, { x: `${dataPoint[0]}`, y: recordsAvg }];
    });
    /**
     * Push the complete reduced array into the local state
     */
    setReducedMetricValues(reducedData);
}, [metricValues]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda