Sorting Data Points based on X-values in Line Chart - CanvasJS JavaScript Charts

Sorting Data Points based on X-values in Line Chart - CanvasJS JavaScript Charts

by canvasjs

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->

<div id="chartContainer" style="height: 360px; width: 100%;"></div>

JavaScript

function compareDataPointX(dataPoint1, dataPoint2) {
  return dataPoint1.x - dataPoint2.x;
}

var chart = new CanvasJS.Chart("chartContainer", {
  title: {
		text: "Sort Datapoints by x-value"
  },
  data: [
    {
      type: "line",
      dataPoints: [
        { x: 10, y: 71 },        
        { x: 30, y: 50 },
        { x: 20, y: 55},
        { x: 40, y: 65 },        
        { x: 70, y: 68 },
        { x: 60, y: 28 },
        { x: 50, y: 95 },
        { x: 90, y: 34 },
        { x: 80, y: 14}
      ]
    }
  ]
});

//Comment out the next line to see the difference.
chart.options.data[0].dataPoints.sort(compareDataPointX);

chart.render();