Chartjs-Chartjs multiple lines datasets perfomance issue

0👍

Instead of having Chart.js parsing your preparedData, you could do it on your own.
A slight improvement can then be obtained if you parse the x values only once and assign them to data.labels using Array.map() as follows.

labels: preparedData.map(o => o.x)

Then you can detect all non-x properties from your data objects and map them to datasets.

datasets: Object.keys(preparedData[0])
  .filter(k => k != 'x')
  .map((k, i) => ({
    label: k,
    data: preparedData.map(o => o[k]),
    showLine: true,
    borderColor: colors[i],
    tension: 0.2
  }))

Please take a look at the runnable code below and see how it works.

const colors = ['red', 'green', 'blue', 'gray', 'purple'];
const preparedData = [
  { x: 195, y0: 2, y1: 1, y2: 2, y3: 2, y4: 0 },
  { x: 200, y0: 3, y1: 3, y2: 3, y3: 4, y4: 2 },
  { x: 230, y0: 1, y1: 0, y2: 1, y3: 3, y4: 3 },
  { x: 245, y0: 2, y1: 3, y2: 1, y3: 4, y4: 1 },
  { x: 260, y0: 3, y1: 2, y2: 3, y3: 2, y4: 4 },
  { x: 290, y0: 1, y1: 2, y2: 4, y3: 1, y4: 0 }
];

new Chart('myChart', {
  type: 'scatter',
  data: {
    labels: preparedData.map(o => o.x),
    datasets: Object.keys(preparedData[0])
      .filter(k => k != 'x')
      .map((k, i) => ({
        label: k,
        data: preparedData.map(o => o[k]),
        showLine: true,
        borderColor: colors[i],
        tension: 0.2
      }))
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Leave a comment