Ril*_*ken 8 javascript arrays multidimensional-array
我无法弄清楚动态生成具有2种不同大小的多维数组的最佳方法.
我们有一个需要一行4个项目的UI,然后是3.这个模式会重复,直到数组中的内容被用完为止.
这基本上就是我需要做的事情:
// Convert
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
// to
const rows [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11], [12, 13, 14]];
Run Code Online (Sandbox Code Playgroud)
这就是我目前所拥有的,它只是将数组转换为4.
const buildRows = (arr, length) => arr.reduce((rows, val, i) => (
i % length == 0 ? rows.push([val]) : rows[rows.length-1].push(val)
) && rows, []);
Run Code Online (Sandbox Code Playgroud)
提前感谢您的帮助.
ibr*_*rir 10
以下解决方案将改变(清空)输入数组array:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
let result = [], i = 0;
while(array.length) { // while there still items in array (array is continually getting shrunk untill it is emptied (array.length === 0))
result.push(array.splice(0, i++ % 2? 3: 4)); // cut the first 3 or 4 numbers depending on the index of the cut i (if i is pair, then cut 4, else, cut 3) and then push the cut-out items into the result array
}
console.log(result);Run Code Online (Sandbox Code Playgroud)
如果你不想改变它,那么使用slice而不是splice,但你必须提供切割的起始索引:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
let result = [], i = 0, next = 0; // next will be the index from which the cut will start
while(next < array.length) { // there is still items to cut
let itemsToCut = i % 2? 3: 4; // determine how many items we are going to cut
result.push(array.slice(next, next + itemsToCut)); // cut the items between next and next + itemsToCut
next += itemsToCut; // increment next by the number of cut-out items so it will point to the next item
i++;
}
console.log(result);Run Code Online (Sandbox Code Playgroud)
我建议一个更自我记录的生成器解决方案,其中偶数和奇数行大小不是硬编码,而是通过参数提供:
function* reshape(array, ...rows) {
let i = 0;
while (true) for (let row of rows) {
if (i >= array.length) return;
yield array.slice(i, i += row);
}
}
// Example:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
for (let row of reshape(array, 4, 3)) console.log(row);Run Code Online (Sandbox Code Playgroud)
真正的发电机纯粹主义者将reshape通过首先引入repeat发电机来简化:
function* repeat(iterable) {
while (true) yield* iterable;
}
function* reshape(array, ...rows) {
let i = 0;
for (let row of repeat(rows)) {
if (i >= array.length) break;
yield array.slice(i, i += row);
}
}
// Example:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
for (let row of reshape(array, 4, 3)) console.log(row);Run Code Online (Sandbox Code Playgroud)