我的输入是const
input = [
["A", "B", "C", "D"],
["a", "b", "c"],
[1, 2, 3, 4, 5, 6]
];//预期产出
const output = ["A", "a", 1, "B", "b", 2, "C", "c", 3, "D", 4, 5, 6];所以我编写了一个JavaScript代码来实现输出,
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
let lengthInputArray = input.length;
let outputArray = [];
let lengthArray = [];
for(let indexInput = 0; indexInput < input.length; indexInput++){
lengthArray.push(input[indexInput].length);
}
let maxLen = Math.max(...lengthArray);
for(let maxIndex = 0; maxIndex < maxLen; maxIndex++){
for (var indexArr of input) {
if(indexArr.length <= maxLen){
var tobeInsertValue = indexArr[maxIndex];
if(tobeInsertValue != undefined){
outputArray.push(tobeInsertValue);
}
}
}
}
console.log("outputArray : " + outputArray);有人能建议我解决这个问题的好办法或最佳方法吗?
发布于 2022-05-05 05:00:02
您也可以尝试根据最长的数组索引转置数组,然后使用flat和filter,在没有任何未定义元素(由于数组元素长度不等而未定义)的情况下,生成扁平形式。
let input = [
["A", "B", "C", "D"],
["a", "b", "c"],
[1, 2, 3, 4, 5, 6]
];
let arrayLen = input.map(x => x.length);
let maxLen = Math.max(...arrayLen)
let maxIndex = arrayLen.indexOf(maxLen)
console.log(input[maxIndex].map((_, colIndex) => input.map(row => row[colIndex])).flat().filter(x => x));
发布于 2022-05-05 04:53:22
只要适当地处理结束长度,一个简单的嵌套循环就可以工作:
const input = [
["A", "B", "C", "D"],
["a", "b", "c"],
[1, 2, 3, 4, 5, 6]
];
const maxLen = Math.max(...input.map(({ length }) => length));
let out = [];
for (let i = 0; i < maxLen; i++) {
for (let j = 0; j < input.length; j++) {
if (input[j].length > i) {
out.push(input[j][i]);
}
}
}
console.log(out);.as-console-wrapper { max-height: 100% !important; top: auto; }
我按顺序遍历每个子数组,并以正确的顺序将位于正确位置的值添加到输出数组中。
https://stackoverflow.com/questions/72121988
复制相似问题