Search code examples
arraysnode.jsexceljs

Combining Two Arrays To One in NodeJS


I want to create Excel file that consist of 2 arrays of data with ExcelJS.

I can create the Excel file:

var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});

I can add column headers:

sheet.columns = [{key:"date", header:"Date"}, {key: "quantity", header: "Quantity"}]

I got 2 arrays for these columns:

array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]

I want to combine these 2 arrays to one array like this:

var merged = [{date:"2018-01-04", quantity:25} 
          , {date:"2018-01-06", quantity:32}  
          , {date:"2018-01-08", quantity:42} 
          , {date:"2018-01-09", quantity:48}];

If I can combine, I able to add as row for every data:

for(i in merged){
  sheet.addRow(merged[i]);
}

Then I can create the Excel File:

workbook.xlsx.writeFile("some.xlsx").then(function() {
console.log("xls file is written.");
});

How can I combine two arrays to one If they are ordered? Also, I'm wondering is this the best approach to create excel file in NodeJS?


Solution

  • You can create the new array with

    var array_date = ["2018-01-04", "2018-01-06", "2018-01-08", "2018-01-09"];
    var array_quantity = [25, 32, 54, 48];
    
    var merged = array_date.map((date, i) => ({
        date,
        quantity: array_quantity[i],
    }));