我想将缺少一些值并已从左到右排序的二维数组转换为从上到下排序的新数组,如下例所示。数组中的列和行以及项目数是动态的,可以更改为任意数字。谢谢!
0 | 1 | 2
3 | 4 | 5
6
预计:
0 | 3 | 5
1 | 4 | 6
2 |
输入:
0 | 1 | 2 | 3 | 4
5 | 6
预计:
0 | 2 | 4 | 5 | 6
1 | 3
更新,使用 JavaScript 代码
const input = [[0, 1, 2], [3, 4, 5], [6]];
const expected = convert(input);
// expected = [[0, 3, 5], [1, 4, 6], [2]];
const input = [[0, 1, 2, 3, 4], [5, 6]];
const expected = convert(input);
// expected = [[0, 2, 4, 5, 6], [1, 3]];
更新2
我已经尝试过这种方法:
const input = [[0,1,2],
[3,4,5],
[6]];
const array = flatToArray(input);
console.log("--- Array:---");
console.log(array);
const rows = input.length;
const cols = input[0].length;
const result = [];
for (let i = 0; i < rows; i++) {
result[i] = [];
for (let j = 0; j < cols; j++) {
result[i].push(array[i%rows + j*rows]);
}
}
function flatToArray(input) {
return input.reduce((prev, current) => prev.concat(current), []);
}
console.log("--- Final:---");
console.log(result)
输出:
--- Array:---
[
0, 1, 2, 3,
4, 5, 6
]
--- Final:---
[ [ 0, 3, 6 ], [ 1, 4, undefined ], [ 2, 5, undefined ] ]
我能做到的最好的(……实际上)
function convert ( arr2D )
{
let
xIn = arr2D.flat()
, xRP = arr2D.reduce((a,x,i)=>(a.R[i]=[], x.forEach((_,j)=>a.P.push({i,j})),a),{R:[],P:[]})
;
xRP.P
.sort((a,b)=>(a.j-b.j)||(a.i-b.i))
.forEach( ({i,j})=>xRP.R[i][j]=xIn.shift())
;
return xRP.R
}
const
arrIn = [[0, 1, 2], [3, 4, 5], [6]]
, arrOut = convert( arrIn )
;
console.log( JSON.stringify( arrOut )); // [[0,3,5],[1,4,6],[2]]