简体   繁体   中英

Converting 2D Array Comprehension | m x n size

I am creating a Google App Script and inside I am trying to create a table structure where the cell data is the value of the row heading + the value of the column heading.

I have the following Headings that represent the day and hour...

var tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"]
var tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

I want the contents to be equal to "M0", "M1", "M2", ..., "TH1", ..., etc. So the number of columns is 7 and the number of rows is 10.

I was doing some research into how to do this and found Array Comprehensions, but I quickly found out that those are now NOT supported and we should not use them.

var table = [for (day of tableHeadings) [for (hour of tableHours) day + hour]];

FYI, I don't know if I need to swap the 2 for-clauses yet. I am representing the columns as the days of the week. Also, I don't know if this works on mxn arrays as Google App Script does not allow for this syntax, but if you scroll down to Array comprehensions with two arrays to see an example I used as inspiration.

In most of the documentation, I have been able to find how to convert a single-array Array Comprehension to use maps and filter, but I have not found anything on how to convert a double-array (mxn) Array Comprehension. Some documentation talks about double-array (mxm) Array Comprehension but does not discuss how to convert them.

Is there a simple way to convert a double-array (mxn) Array Comprehension? Just to be very specific, the solution NEEDS to work for (mxn) arrays.

You can achieve this with nested Array#map calls:

 var tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"]; var tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; var result = tableHeadings.map(function(day) { return tableHours.map(function(hours) { return day + hours; }); }); console.log(result); 

And using ES6 arrow functions you can have a one liner:

 const tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"]; const tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; const result = tableHeadings.map((day) => tableHours.map((hours) => day + hours)); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM