Search code examples
javascriptchartscanvasjs

Loop to create lines chart in canvasjs


I have an array Object:

  total = 
   [
    {
      date: 5/12/2017,
      count: 5,
      type: A
     },
     {
      date: 5/15/2017,
      count: 15,
      type: A
     },
     {
      date: 5/12/2017,
      count: 4,
      type: B
     },
     {
      date: 5/15/2017,
      count: 5,
      type: C
     }..
    ]

I wondering how to loop them in a line chart using CanvasJS, each line presents each type, the x-axis presents date, the y-axis presents count

Here is what I have so far:

     var chart = new CanvasJS.Chart("chartContainer",
        {
            title: {
                text: "My Counts"
            },
            axisX: {
                title: "Date",
            },
            axisY: {
                title: "Count"
            },
            data: []
           });

Solution

  • You can run a for loop over your array and store dataPoints in different variable to later use it in your chart.

    var dps1 = [];
    var dps2 = [];
    var dps3 = [];
    
    for(var i = 0; i < total.length; i++) {
        if(total[i].type === "A") {
            dps1.push({x: new Date(total[i].date), y: total[i].count});
        } else if(total[i].type === "B") {
            dps2.push({x: new Date(total[i].date), y: total[i].count});
        } else if(total[i].type === "C") {
            dps3.push({x: new Date(total[i].date), y: total[i].count});
        }
    }
    

    Once you store you dataPoints, you'll need to use it in your chart.

    data: [{
        type: "line",
        dataPoints: dps1
    }, {
        type: "line",
        dataPoints: dps2
    }, {
        type: "line",
        dataPoints: dps3
    }]