Chartjs-Why is my data on chartjs not starting from the data that it should

0👍

Look at your code, at no point chart.js has the link between the labels and their value for a given dataset. It can’t guess it.
So it simply shows the elements in the order in which you added them to their datasets, and shows the labels in the order you put them into items

You should configure chart.js to use dates for the x-axis.

See : https://www.chartjs.org/docs/latest/axes/cartesian/time.html

0👍

The data object to which you are passing an array item_val and item_val_2 are quite simply that, an array of numbers. They have no knowledge of the labels or where they should go on the chart. Since you have two datasets, they both populate in the order of the labels from let to right. You should pass in 0 values to the arrays where the date is not applicable to the purchases.

0👍

As Loïc says, you need to set the x axis to time and make the data the format expected by chart.js for time data.

so for the data:

var item_val = [];
var item_val_2 = [];
var total = 0;
data['awal'].forEach(element => {
    item_val.push({t: new Date(element.order_date).toLocaleString('en-us', options), y:element.total});
    total += parseInt(element.total);
});

data['akhir'].forEach(element => {
    item_val_2.push({t: new Date(element.order_date).toLocaleString('en-us', options), y:element.total});
    total += parseInt(element.total);
});

and for the x axis, add this as the options parameter for your chart:

options:{
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        displayFormats: {
          day: 'MMM D YYYY'
        }
      }
    }]
  }
}

Leave a comment