score:1

Accepted answer

so, after a bit of trying i've found a solution that could be tailored perfectly for you needs.

var ctx = document.getelementbyid("mychart");
var mychart = new chart(ctx, {
  type: 'bar',
  data: {
    labels: getpreviousmonths(),
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'chiffre d\'affaire - année 2018'
    },
    scales: {
      xaxes: [{
        type: 'time',
        time: {
          unit: 'month'
        },
        scalelabel: {
          display: true,
          labelstring: 'date'
        }
      }],
      yaxes: [{
        scalelabel: {
          display: true,
          labelstring: 'value'
        }
      }]
    }
  }
});

function getpreviousmonths() {
  var months = [];
  months = array.apply(0, array(12)).map(function(_,i){return moment().month(i).toisostring()})
  return months;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.7.2/chart.min.js"></script>
<canvas id="mychart"></canvas>

this is the same function you had but uses the function moment().month() that returns an array of months and it formats it with the format you wanted. (it shows only half months in this snippet because it can't extent through the entire page and cuts half months, should work on a full window)

i really don't understand why your code was not working, i guess something happens when you reverse the order but anyway this should work. cheers!

=== edit ===

as suggested in the comments, the formatting was removed and was added the function toisostring(). this is because before, the date was getting transformed to a jsdate which is not supported by all browsers.


Related Query

More Query from same tag