来自数组数组的块数据

Chunk data from array of arrays

在将此标记为另一个问题的回答之前请注意这是一个数组数组,而不是平面数组,另外,我给出的数字是一个例子,我有只是展示它们,这样您就可以直观地看到发生了什么。

我正在尝试遍历数组数组。 我有以下数组:-

[
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [3, 2, 1, 6, 5, 4, 9, 8, 7],
   [6, 5, 4, 9, 8, 7, 3, 2, 1],
   [7, 8, 9, 3, 2, 1, 6, 5, 4]
]

如何将此数组转换为 3x3 的块,例如:-

[
   [1, 2, 3, 1, 2, 3, 1, 2, 3],
   [4, 5, 6, 4, 5, 6, 4, 5, 6],
   [7, 8, 9, 7, 8, 9, 7, 8, 9],
   [3, 2, 1, 6, 5, 4, 9, 8, 7],
   [6, 5, 4, 9, 8, 7, 3, 2, 1],
   [7, 8, 9, 3, 2, 1, 6, 5, 4],
]

正如您从上面的数组中看到的那样,我使用每个数组的前 3 个值对其进行了分块,然后是每个数组的第二个 3n,最后是每个数组的最后 3n。

所以数组将像下面这样分块:-

1 2 3 | 4 5 6 | 7 8 9
1 2 3 | 4 5 6 | 7 8 9
1 2 3 | 4 5 6 | 7 8 9
---------------------
3 2 1 | 6 5 4 | 9 8 7
6 5 4 | 9 8 7 | 3 2 1
7 8 9 | 3 2 1 | 6 5 4

我尝试遍历每一行并在达到增量时重置列数并增加行数,但这没有用。

如果这有帮助,我可以用以前的尝试更新问题吗? 另外请注意,数组的大小不同,但总是可以被特定数字整除,对于上面的示例,我选择了数字 3.

我已经用更多信息更新了问题。 数组的数组将始终被特定数字整除,此示例显示可整除的数字 3.

这可以根据这个问题用一个块来解决Split array into chunks combined with a zip as per this Javascript equivalent of Python's zip function

这样做的好处是可以逆向操作回到原来的状态。

/** @see:  */
function chunk(array, chunk) {
    let result = [];
    for (let i = 0; i < array.length; i += chunk) {
        result.push(array.slice(i, i + chunk));
    }
    return result;
}

/** @see:  */
function zip(...rows) {
    return [...rows[0]].map((_, c) => rows.map((row) => row[c]));
}

const array = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [3, 2, 1, 6, 5, 4, 9, 8, 7],
    [6, 5, 4, 9, 8, 7, 3, 2, 1],
    [7, 8, 9, 3, 2, 1, 6, 5, 4],
];

const result = chunk(array, 3)
    .flatMap((innerChunk) =>
        zip(...innerChunk.map((arr) => chunk(arr, 3)))
        .map((arr) => arr.flat())
    );

console.log(result.map((a) => a.join(', ')));

// Allows the result to be reverted to the original
const reversed = chunk(result, 3)
    .flatMap((innerChunk) =>
        zip(...innerChunk.map((arr) => chunk(arr, 3)))
        .map((arr) => arr.flat())
    );

console.log(reversed.map((a) => a.join(', ')));

您可以使用嵌套循环,每次根据外部数组的大小对数组进行切片。

const arr = [
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [1, 2, 3, 4, 5, 6, 7, 8, 9]
];

let out = [];
for(let i in arr) { out.push([]);}

arr.forEach((e, i) => {
    let scale = e.length / arr.length;
    for(let j in arr)
    {
      out[j] = out[j].concat(e.slice(j * scale, j * scale + scale));
    }
});

console.log(out);

这是您编辑前的原始数组:

const arr = [
   [1, 3, 2, 5, 2, 4, 3, 6, 8],
   [1, 4, 3, 6, 7, 3, 6, 4, 5],
   [2, 4, 1, 4, 6, 3, 7, 9, 7]
];

let out = [];
for(let i in arr) { out.push([]);}

arr.forEach((e, i) => {
    let scale = e.length / arr.length;
    for(let j in arr)
    {
      out[j] = out[j].concat(e.slice(j * scale, j * scale + scale));
    }
});

console.log(out);