Chartjs-How to use forEach loop on my array to plot x and y variables on my chart (Chart.js)

1πŸ‘

βœ…

I think you are looking for a scatter chart but not line chart

const config = {
      data: {
          datasets: [{
              type: 'scatter',
              label: 'Low Limit',
              data: newArr.map(a => { return { x: a[0], y: a[1]  } }),
              fill: false,                            
              borderColor: 'rgb(0, 128, 0)',
          }]
      },
      options: {
          scales: {
               y: {
                    beginAtZero: true
               }
          }
       }
};

Example JSFiddle

3πŸ‘

you can try like this.

 newArr.forEach((items) => 
            console.log(items)
            let values = {
                items[0], items[1]
             }
let ctx = document.getElementById('myChart').getContext('2d');
                let myChart = new Chart(ctx, values);
        )

0πŸ‘

I think the problem is because you are creating the config property in each iteration on the array.

In this code bellow, I suggest you use β€˜map’ only for defining the properties x and y and pass them to the config once.

const config = {
    data: {
        datasets: [{
            type: 'line',
            label: 'Low Limit',
            data: newArray.map(([x, y]) => { x, y }),
            fill: false,
            pointRadius: 0,
            tension: 0.1,
            borderColor: 'rgb(0, 128, 0)',
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
};

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, config);

0πŸ‘

You don’t need a for loop at all if you use Object.fromEntries()

const entries = new Map(newArray);
const obj = Object.fromEntries(entries);

var data = {
    datasets: [{
        label: 'My First Dataset',
        data: obj,
        fill: false,
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1,
    }]
};

const config = {
    type: 'line',
    data: data,
    options: { 
        animation: false,
    }
};


var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, config);

Here is a JSFiddle.

Leave a comment