【问题标题】:I want to move the elements inside multiple list of arrays around我想移动多个数组列表中的元素
【发布时间】:2026-02-12 04:40:01
【问题描述】:

我有这个数组

0: (5) ["2", "X", "8", "11", "15"] 
1: (5) ["1", "5", "X", "X", "14"]
2: (5) ["X", "4", "7", "10", "13"]
3: (5) ["X", "3", "6", "9", "12"]

我想将数字 1 移动到数字 2 所在的位置,以便该数组返回

0: (5) ["1", "X", "8", "11", "15"]
1: (5) ["2", "5", "X", "X", "14"]
2: (5) ["X", "4", "7", "10", "13"]
3: (5) ["X", "3", "6", "9", "12"]

这个数组集合是一次性返回的,所以我想在它返回后更改位置。

我正在使用 JavaScript。 谢谢大家。

我试过了

Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};

但这会移动整个行,即将数组 0 移动到数组 1

【问题讨论】:

    标签: javascript arrays angularjs


    【解决方案1】:

    找到两者的外部数组索引和内部数组索引,然后切换它们:

    const input = [
     ["2", "X", "8", "11", "15"] ,
     ["1", "5", "X", "X", "14"],
     ["X", "4", "7", "10", "13"],
     ["X", "3", "6", "9", "12"]
    ];
    
    const getLoc = char => {
      const arrIndex = input.findIndex(subarr => subarr.includes(char));
      const subArrIndex = input[arrIndex].indexOf(char);
      return [arrIndex, subArrIndex];
    };
    const move = (char1, char2) => {
      const [loc1, loc2] = [char1, char2].map(getLoc);
      
      [
        // switch position of first character:
        input[loc1[0]][loc1[1]],
        // and position of second character:
        input[loc2[0]][loc2[1]]
      ] = [
        // with position of second character:
        input[loc2[0]][loc2[1]],
        // and the first character:
        input[loc1[0]][loc1[1]]
      ];
    };
    
    move('2', '1');
    console.log(input);

    【讨论】:

      【解决方案2】:

      您可以使用findIndex从各自的数组中找到21的第一个索引,然后替换它。否则,如果您只想在特定索引处替换元素,那么您可以直接定位数组和索引并替换它

      let data = [
        ["2", "X", "8", "11", "15"],
        ["1", "5", "X", "X", "14"]
      ];
      
      
      let find2In1 = data[0].findIndex(item => item === "2");
      let find1In2 = data[1].findIndex(item => item === "1");
      data[0][find2In1] = "1";
      data[1][find1In2] = "2";
      
      console.log(data)

      【讨论】:

      • 谢谢,这似乎可行,但现在,您正在指定值本身。如果数字与此示例相同,我想将第一个字符移动到第二个字符,如下所示: 0: (5) [2, -1, 0, 0, 0] 1: (5 ) [0, 2, -1, -1, 2] 2: (5) [-1, 0, 0, 0, 0] 3: (5) [-1, 2, 0, 0, 0]跨度>
      • 谢谢,我可以通过创建另一个向量函数来解决它,它应该返回 return [1, 0];因为我注意到当我将 2 和 0 传递给 switchVectorValues 时,它总是选择第一行来改变这两个值,所以因为我知道我想要交换的行,所以我只是在向量返回值中指定了它。非常感谢。
      【解决方案3】:

      从您的样本来看,您似乎需要交替使用 1 和 2。

      输入

      0: (5) ["2", "X", "8", "11", "15"] 
      1: (5) ["1", "5", "X", "X", "14"]
      2: (5) ["X", "4", "7", "10", "13"]
      3: (5) ["X", "3", "6", "9", "12"]
      

      输出

      0:(5) ["1", "X", "8", "11", "15"]
      1: (5) ["2", "5", "X", "X", "14"]
      2: (5) ["X", "4", "7", "10", "13"]
      3: (5) ["X", "3", "6", "9", "12"]
      

      您可以搜索每个数组并使用 forEach 执行此操作。

      a.forEach((item) => {
      
         if (item === "1")
            item = "2"
         else
            if (item === "2")
                item = "1"
      })
      

      【讨论】:

        最近更新 更多