0

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?

ilvthsgm
  • 586
  • 1
  • 8
  • 26
  • Possible duplicate of [Javascript equivalent of Python's zip function](https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) – Pac0 Jan 17 '18 at 08:17

2 Answers2

5

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],
}));
Steffen Schmitz
  • 860
  • 3
  • 16
  • 34
1
array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]

var merged=[];

for(var i=0;i<array_date.length;i++){
  merged.push({date:array_date[i], quantity:array_quantity[i]});
}

console.log(merged);
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71