Home > OS >  How do I populate two variables using foreach in js?
How do I populate two variables using foreach in js?

Time:12-30

function populateTable(data,monthly) {
            var table = $('#file_export').DataTable();
            table.clear().draw();
            data.forEach(element => {
                table.row.add([
                    element.date,
                    element.dailycount,
                    // monthly.monthlycount,

                ]).draw(false);
            });


        }

the following query returns the result of only the data variable, but i need a record of monthly too.It may be the case that the rows of both data and monthly won't be equal.what is the best idea to populate both results in a table.

CodePudding user response:

One option could be to loop through both data and monthly arrays, and for each element in data, check if there is a corresponding element in monthly with the same date. If there is, add both elements to the table row. If there isn't, just add the element from data to the table row.

Here is an example of how this could be implemented:

function populateTable(data, monthly) {
  var table = $('#file_export').DataTable();
  table.clear().draw();
  data.forEach(element => {
    let monthlyCount = 0;
    for (let i = 0; i < monthly.length; i  ) {
      if (monthly[i].date === element.date) {
        monthlyCount = monthly[i].monthlycount;
        break;
      }
    }
    table.row.add([
      element.date,
      element.dailycount,
      monthlyCount
    ]).draw(false);
  });
}
  • Related