我有一个函数,它按行从二维数组中选择所有元素并返回一个一维数组。该数组具有可变数量的列和行。
例子:
let arr = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
回报:
[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12]
我想出的功能:
convertList = (list) => {
let result = [];
let listTotalEntries = R.sum(R.map(R.length)(list));
let mod = R.modulo(R.__, list.length);
let counterRow = -1;
for (let i = 0; i < listTotalEntries; i++) {
if (mod(i) === 0) {
counterRow++;
}
if (list[mod(i)][counterRow]) {
result.push(list[mod(i)][counterRow]);
console.log(list[mod(i)][counterRow]);
}
}
console.log(result);
return result;
};
问题:此函数仅适用于方阵 - 如何使其适用于包含数组的可变长度?
例子:
let arr = [
[1, 2],
[],
[9, 10, 11, 12]
];
应该返回:
[1, 9, 2, 10, 11, 12]
谢谢你的帮助!
莫夫