0
votes

I want to build some charts using Chart.js and ng2-charts. I have an array of data (week). I would like to know how to build an array of revenu-values and budget-values according to each date. These values will be shown on the Y-axis of the graph and the X-axis contains the labels ( [01, 02, 03, 04, 05, ..., 31] ) which are the month dates :

week = [
         {
            date = "2019-03-01",
            revenu = 1000,
            budget = 800
         },
         {
            date = "2019-03-02",
            revenu = 1000,
            budget = 800
         },
         {
            date = "2019-03-03",
            revenu = 1000,
            budget = 800
         },
         {
            date = "2019-03-04",
            revenu = 1000,
            budget = 800
         },
         ...
       ];
       

public monthChartLabels= [01, 02, 03, 04, 05, ..., 31];
public monthChartData = [
  {
    data: [ ? ] // Array of revenu-values according to each date
  },
  {
    data: [ ? ] // Array of budget-values according to each date
  }  
];
 
<canvas
        baseChart
        [chartType]=" 'line' "
        [datasets]="monthChartData"
        [labels]="monthChartLabels"
        [options]="monthLabels"
        [legend]="true"
        (chartHover)="onChartHover($event)">
</canvas>
1

1 Answers

0
votes

Shalom Eli, you should map your original data to the chart's data arrays: week.map(e => e.revenu) for the revenu dataset, and week.map(e => e.budges) for the budget dataset.

Update

Based on your comment, you want to convert your week array to a map keyed by the day of the month of each record:

week.reduce((acc,v)=> ({
  ...acc,
  [new Date(v.date).getDate()]: v
}), {})

And then use your labels array to fetch each value from this map:

revenuData = labels.map(r => this.weekMap[+r] && this.weekMap[+r].revenu);
budgetData = labels.map(r => this.weekMap[+r] && this.weekMap[+r].budget);

See this updated stackblitz: https://stackblitz.com/edit/ng2-charts-line-template-3dfmxn

enter image description here