简体   繁体   中英

How can I tersely create JavaScript array of arrays, with different lengths for each array (each row has a different, specified length)?

I need to create a Javascript array to represent the layout of tables in a room:

0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 
17 18 19

I have done this so far:

this.CHART = Array(4).fill(0).map((x, i) => Array(5).fill(0).map((y, j) => j));

...which produces this array:

0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

This is very close to the requirement, but now I'm in over my head trying to assign the correct values, and assigning a different size to each array.

This smelly version works to create the required array, but I think there must be a better way, that will be helpful to me and to others reading this post in the future:

ROW_1 = [];
ROW_2 = [];
ROW_3 = [];
ROW_4 = [];

const ROW_1_SIZE = 5;
const ROW_2_SIZE = 7;
const ROW_3_SIZE = 5;
const ROW_4_SIZE = 3;

ROW_1 = Array(ROW_1_SIZE).fill(0).map((x, i) => i + 1);
ROW_2 = Array(ROW_2_SIZE).fill(0).map((x, i) => i + 1 + ROW_1_SIZE );
ROW_3 = Array(ROW_3_SIZE).fill(0).map((x, i) => i + 1 + ROW_1_SIZE + ROW_2_SIZE );
ROW_4 = Array(ROW_4_SIZE).fill(0).map((x, i) => i + 1 + ROW_1_SIZE + ROW_2_SIZE + ROW_3_SIZE );

You could keep a counter for the values in a closure.

 var lengths = [5, 7, 5, 3], result = lengths.map((i => length => Array.from({ length }, _ => i++))(0)); result.forEach(a => console.log(...a));

Without IIFE

mapWithValue is a function which expects a value and returns a callback for Array#map for creating an array and maps increased values.

 const mapWithValue = i => length => Array.from({ length }, _ => i++); var lengths = [5, 7, 5, 3], result = lengths.map(mapWithValue(0)); result.forEach(a => console.log(...a));

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