Chartjs-How to Fill array with 0 if data is not present?

2👍

You can play with this Plunker, i think it’ll be a great point for starting, you can improve it and adjust it to your needs.

 while (i < 12){
    if(data[prev] && i == data[prev][prev].month) {
      array.push(data[prev][prev]);
      prev++;
    } else {
      array.push({i:{month: i, profit: 0}});
  }
i++;

}

So that is basically going to be your function so you just have to modify the final array to match the chart.js format, hope this will be helpful for you

0👍

Check out this fiddle

Summary:
Basically, sanitize your data. Loop over your data and push whatever data you have into an array. Then loop over an array of 12 (12 months) and put 0 where ever you find a hole in the array.

data.forEach(function (item) {
  // -> iterate over all keys in the item
  //    -> for every key get the month and profit and put into result
  //    -> result[month] = profit
});

Now fill the holes

// create an empty array of size 12
Array.apply(null, {length: 12 }).forEach(function (i, month) {
  // -> if result[month] == null
  //    -> that mean no data for that month is present.
  //    -> put that in the result with profit 0
  //    -> result[month] == 0
});

Use result array in the chart.

Leave a comment