Search code examples
javascriptarraystypescriptamchartsamcharts4

Issue with multiple loops and pushing to array


I am using Angular/Typescript with the amcharts library (version 4), specifically the multi line graph. In building the chart data, it only seems to work correctly with a single push to the chart array.

Here is my code:

 chart.data = [];

        let hvacData: any = '';
        for (let i = 0; i < this.chartTradeData['HVAC'].length; i++) {
          const newDate = new Date(this.chartTradeData['HVAC'][i]['calendarDate']);
          hvacData = this.chartTradeData['HVAC'][i]['revWorkDay'];
          hvacData = parseInt(hvacData);
          chart.data.push({
            date: newDate,
            hvacData
          });
        }

        let plumbingData: any = '';
        for (let i = 0; i < this.chartTradeData['Plumbing'].length; i++) {
          const newDate = new Date(this.chartTradeData['Plumbing'][i]['calendarDate']);
          plumbingData = this.chartTradeData['Plumbing'][i]['revWorkDay'];
          plumbingData = parseInt(plumbingData);
          chart.data.push({
            date: newDate,
            plumbingData
          });
        }

        let electricalData: any = '';
        for (let i = 0; i < this.chartTradeData['Electrical'].length; i++) {
          const newDate = new Date(this.chartTradeData['Electrical'][i]['calendarDate']);
          electricalData = this.chartTradeData['Electrical'][i]['revWorkDay'];
          electricalData = parseInt(electricalData);
          chart.data.push({
            date: newDate,
            electricalData
          });
        }

Doing it as above only renders the first line on the graph. I need to figure out how to do all these pushes at once so that it looks like this after the loops:

  chart.data.push({
        date: newDate,
        hvacData,
        plumbingData,
        electricalData
      });
    }

The object I am iterating over looks like this:

enter image description here


Solution

  • You need to use the addData method:

    chart.addData([...]);
    

    I recommend you to try add arrays with all the data instead of one item at a time.

    Check more about incremental updates here.