assign data points to Chart.js

I have written a piece of code that counts the occurrences of each date in an array:

let month = [];
let current;
let count = 0;
chartDates = chartDates.sort()

for (var i = 0; i < chartDates.length; i++) {
    month.push(chartDates[i].split('-')[1]);
    if (chartDates[i] != current) {
        if (count > 0) {
            console.log(current + ' times ' + count);
        }
        current = chartDates[i];
        count = 1;
    } else {
        count++;
    }
}
if (count > 0) {
    console.log(current + 'times ' + count);
}

This is the output I am getting:

2010-02-08 times 1
2010-02-11 times 1
2010-03-05 times 1
2010-03-08 times 1
2017-09-19 times 3
2017-12-26 times 1

Now, I want to use this data to create a bar chart using chart.js. The "labels" should be the dates and the "data" should represent how many times each date occurs. I tried using year = []; and then year.push(current); to avoid repeating equal dates within each loop iteration, but it did not work.

Can anyone help me fix this issue?

Here is my chart's configuration:

var myChart = new Chart(ctx, {
               type: 'bar',
               data: {
                   labels: chartDates,
                   datasets: [{
                       label: month,
                       data: month,
                 .....

Answer №1

After extensive troubleshooting, I believe I have solved 95% of the issue at hand. I implemented a new array where I store the current count of "occurrences" to create pairs of (date - occurrences). - However, there is a minor glitch: the last date repeats! This is due to the final if(count > 0) statement. If I omit pushing the year value, even though my console log shows the correct array of dates, only 3 are displayed in the chart (?) Below is the code snippet along with the output from the console log and the corresponding chart!

ts

let month = [];
            let current;
            let count = 0;
            let year = [];
            let values = [];
           chartDates = chartDates.sort()

           for (var i = 0; i<chartDates.length; i++)
           {
               month.push(chartDates[i].split('-')[1]);
               if (chartDates[i] != current)
               {
                   if (count > 0)
                   {
                       //console.log(current + ' times ' + count);
                       values.push(count);
                   }
                   current = chartDates[i];
                   year.push(current);
                   count = 1;
               }
               else
                   {
                   count++;
                   }
           }
           if (count > 0)
           {
               //console.log(current + 'times ---' + count);
               //year.push(current);
               values.push(count);
           }


           console.log('datas: '+year+ ' contadores '+ count);

chart inside ts var myChart = new Chart(ctx, { type: 'bar', data: { labels: year, datasets: [{ label: year, data: values ...

Console log:

datas: 2010-02-08,2010-02-11,2010-03-05,2010-03-08,2017-09-19,2017-12-26 contadores 1

The visual output can be seen below: https://i.sstatic.net/NAaCU.png

FIX EDIT : Adding year.push(current); resolves the issue, although it leads to the last label being repeated without any associated value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular - Automatically blur input field in a Reactive Form

I'm encountering a strange problem. Check out the demo .ts import { Component } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './a ...

Ways to prevent a user from reaching a specific page by entering the URL in a react and typescript application

Is there a way to restrict access to a specific page with the URL "myurl/view"? I want only admin users to be able to view this page, while preventing other users from accessing it. Currently, when the view button is clicked, it redirects to the URL "/vie ...

Develop a child interface within Typescript

I am unsure if the term sub interface is correct, but my goal is to develop an interface that inherits all properties from the super interface except for some optional ones. Despite referring to the TypeScript documentation for interfaces, I was unable to ...

Is it possible for me to exclude generic parameters when they can be inferred from another source?

Imagine having a scenario like this: type RecordsObject<T, K extends keyof T> = { primaryKey: K; data: Array<T>; } where the type K is always derived from the type T. Oftentimes, when I try to declare something as of type RecordsObject, ...

What is the best way to pass a conditional true or false value to React boolean props using TypeScript?

I am currently utilizing the Material UI library in combination with React and Typescript. Whenever I attempt to pass a conditional boolean as the "button" prop of the component, I encounter a typescript error stating: Type 'boolean' is not assi ...

Maintain the nullability of object fields when casting

I have been working on a type called DateToNumber that converts all the Date properties of an object to number. Here is what I have come up with so far: type LiteralDateToNumber<T> = T extends Date ? number : T extends Date | null ? number | nu ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

Break down Angular modules into smaller parts with the help of webpack

As I work on breaking down a huge Angular project with numerous components, I'm faced with the challenge of dealing with this large module that ideally shouldn't be there in the first place. Unfortunately, due to the current stage of the project, ...

WebStorm is not implementing the exclude option as specified in the tsconfig.json file

Is there a way to exclude a directory from TypeScript compilation in WebStorm? Despite specifying the exclusion in the tsconfig.json file, it seems that WebStorm doesn't respect the setting and compiles everything in the root directory. However, runn ...

Unable to set up enzyme adapter

Currently, I am in the process of setting up the enzyme adapter for testing purposes. The code snippet that I have is quite straightforward: import * as enzyme from 'enzyme'; import * as Adapter from 'enzyme-adapter-react-16'; enzyme. ...

Stop non-logged-in users from accessing page content rendering

Lazy loading is being used in my application to render pages. { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivate: [AuthGuard] } The problem arises when the user types www.mydomain.com/dashbo ...

Trouble arises when trying to use add event listener on dynamically generated elements through (*ngFor)

Expanding the Accordion View Issue Whenever the section button is clicked, the event listener userSelection[i].addEventListener changes the id to 'open', thus expanding the accordion. This functionality works without any issues when not using t ...

Reasons Why Optional Chaining is Not Utilized in Transpiling a Node.js + TypeScript Application with Babel

Currently, I am delving into Babel in order to gain a deeper understanding of its functionality. To facilitate this process, I have developed a basic API using Node.js and TypeScript. Upon transpiling the code and initiating the server, everything operates ...

Navigating Between Pages with Parameters in Ionic 2 (starter app)

I have an Ionic 2 project with a blank template containing a page that displays a list. Upon clicking on an item in the list, the user should be able to view more details about that specific item. Below are the files related to the list: list.html: <i ...

Angular 9 - Button unable to be clicked under certain conditions

I have a webpage that contains a lot of information, and I would like to make it easier for the user to show/hide specific parts by clicking on buttons. Check out this stackblitz to see what I've done. Here's a brief summary of the code: <but ...

Unfortunately, ng2-datepicker does not currently have support for Angular 4

I am in the process of upgrading from Angular version 2.4.0 to Angular 4, and encountered some peer dependency errors along the way: Attempting to install the latest datepicker component: npm install ng2-datepicker –save Resulted in the following erro ...

Sending input in a nested event listener

I am currently utilizing Highcharts for the purpose of showcasing an interactive map with custom countries. I have a specific requirement to enable the drilldown functionality, which involves clicking on a country to zoom in on another map displaying inter ...

Populating a Modal Popup with an Angular 2 Module

I am currently implementing angular 2 with bootstrap. On my dashboard page, I have a specific requirement where when a user clicks on any link, a new module should appear in a modal popup. Can you provide guidance on how to accomplish this task? Since my ...

I encountered an issue when trying to dynamically add a text field in Angular 2. The error message received was "ERROR TypeError: Cannot read property '0' of

I am currently utilizing Angular2 in my project, and I am attempting to dynamically add a text field. However, I keep encountering an error: Error Message (TS): ngOnInit() { this.myForm = this._fb.group({ myArray: this._fb.array([ ...

Processing a list in Angular using Observables

In my Angular12 application, I am fetching data from a Firebase Realtime DB using AngularFire. To streamline my code and ensure consistency, I have implemented a DAO service to preprocess the retrieved data (e.g., converting string dates to Date objects). ...