Chartjs-Using loops to create data arrays

0👍

Sure, its a fine way to populate an array. If you want to make it run just a little faster, you can just assign the tata value directly to the index rather than calling array.push.

const arr2 = [pmt, ((1 + r) * pmt)];

for (let i = 1; i < n; i++) {
  arr2[i + 1] = Math.round((1 + r) * (pmt + arr2[i]));
}

In js, array’s are sparse. So you can take advantage of that by just assigning the values to an index vs pushing onto the array.

If you wanted to make this even faster, and if you can know what the end value will be from the beginning, you can iterate backwards like:

for (let i = endLength; i--;) {
  arr2[i] = // do calculations here
}

0👍

Considering that your code runs on O(n) time, I am positive it should be ok, and that there is no way you could make this faster (since you need to create every point to be plotted).

Unless your chart is static, in a sense that it does not depend on your database data, or some kind of user interaction, you will always have to create new points and in this case there is really nothing you could do.

most likely the slow step will be on charts.js part, which is creating the DOM nodes so that it can paint the chart in the screen.

Another option would be to store the array data on locaStorage and use it as a cache so that if the user hit this route again, you would first check for the data on your locaStorage and if not there you could build it.

that would be overkill in my opnion, O(n) time complexity to build and array is fine and expected, even for thousands of points.

Leave a comment