首页 > 解决方案 > 数组操作实现模式(JavaScript)

问题描述

我有两个数组都是可变长度的,我想实现一个模式,我已经实现了但对我的解决方案不满意。我相信可能有更好的方法来实现同样的目标。

const logic = (outerArray, innerArray) => outerArray.map((outerVal, OuterIndex) => {
  return innerArray.map((innerVal, innerIndex) => {
    const currentSlideIndex = OuterIndex + 1;
    if (innerArray.length < 6 && innerIndex + 1 === currentSlideIndex) return true;
    if (innerArray.length === 6) {
      if (innerIndex < 4 && innerIndex + 1 === currentSlideIndex) return true;
      // return false if currentslide is greater than four and less than last two slides
      if (currentSlideIndex > 4 && currentSlideIndex < outerArray - 1 && innerIndex === 3) {
        return true;
      }
      if (innerIndex === 4 && currentSlideIndex === outerArray - 1) return true;
      if (innerIndex === 5 && currentSlideIndex === outerArray) return true;
    }

    return '';
  });
});

预期成绩

  1. 如果 innerArray 长度小于或等于 6 它应该返回长度数组作为 innerArray 并且输出应该看起来像

    逻辑([1,2,3,4,5],[1,2,3,4,5])

    预期产出

    [
        [true, "", "", "", ""],
        ["", true, "", "", ""], 
        ["", "", true, "", ""], 
        ["", "", "", true, ""], 
        ["", "", "", "", true]
    ]
    
  2. 如果 outerArray 长度大于 6,那么它应该对 3 索引工作相同,并且应该为所有 outerArray 索引的索引 4 返回 true,并在最后两个索引处恢复。

    逻辑([1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6])

    预期产出

    [
        [true,"","","","",""],
        ["",true,"","","",""],
        ["","",true,"","",""],
        ["","","",true,"",""],
        ["","","",true,"",""],
        ["","","",true,"",""],
        ["","","",true,"",""],
        ["","","",true,"",""],
        ["","","","",true,""],
        ["","","","","",true]
    ]
    

标签: javascript

解决方案


我会将您的代码分成两个函数。第一个将返回 outerArray 的每个值的列索引,如下所示:

const getColumnIndexes = (array) => {
    // Get first 3 items
    let columnIndexes = array.slice(0, 3);
    // Get items in 4th column
    columnIndexes = columnIndexes.concat(array.slice(3, Math.max(4, array.length - 2)).map(() => 4));
    // Get last 2 items
    columnIndexes = columnIndexes.concat(array.slice(Math.max(4, array.length - 2), array.length).map((val, index) => 5 + index));
    return columnIndexes;
};

然后你的logic功能变得非常简单:

const logic = outerArray => {
    const columnIndexes = getColumnIndexes(outerArray);
    return outerArray.map((val, lineIndex) => {
        return Array(Math.min(6, outerArray.length)).fill().map((_, i) => i === columnIndexes[lineIndex] - 1 ? true : "");
    });
};

如果我理解正确,你实际上不再需要这个 innerArray 了。

logic([1, 2, 3, 4, 5]);

[
    [true, "", "", "", ""],
    ["", true, "", "", ""], 
    ["", "", true, "", ""], 
    ["", "", "", true, ""], 
    ["", "", "", "", true]
]

logic([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

[
    [true,"","","","",""],
    ["",true,"","","",""],
    ["","",true,"","",""],
    ["","","",true,"",""],
    ["","","",true,"",""],
    ["","","",true,"",""],
    ["","","",true,"",""],
    ["","","",true,"",""],
    ["","","","",true,""],
    ["","","","","",true]
]


推荐阅读