首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要最佳案例方案

需要最佳案例方案
EN

Stack Overflow用户
提问于 2022-05-05 04:40:46
回答 2查看 56关注 0票数 0

我的输入是const

代码语言:javascript
复制
input = [
  ["A", "B", "C", "D"],
  ["a", "b", "c"],
  [1, 2, 3, 4, 5, 6]
 ];

//预期产出

代码语言:javascript
复制
const output = ["A", "a", 1, "B", "b", 2, "C", "c", 3, "D", 4, 5, 6];

所以我编写了一个JavaScript代码来实现输出,

代码语言: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);

有人能建议我解决这个问题的好办法或最佳方法吗?

EN

回答 2

Stack Overflow用户

发布于 2022-05-05 05:00:02

您也可以尝试根据最长的数组索引转置数组,然后使用flatfilter,在没有任何未定义元素(由于数组元素长度不等而未定义)的情况下,生成扁平形式。

代码语言:javascript
复制
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));

票数 1
EN

Stack Overflow用户

发布于 2022-05-05 04:53:22

只要适当地处理结束长度,一个简单的嵌套循环就可以工作:

代码语言:javascript
复制
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);
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; top: auto; }

我按顺序遍历每个子数组,并以正确的顺序将位于正确位置的值添加到输出数组中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72121988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档