【问题标题】:How to remove the last index in nested array [duplicate]如何删除嵌套数组中的最后一个索引[重复]
【发布时间】:2021-05-15 22:09:22
【问题描述】:
let array=[
  [
    "Test1",
    "4",
    "160496"
  ],
  [
    "Test2",
    "6",
    "38355"
  ],
  [
    "Test3",
    "1",
    "1221781"
  ],
  [
    "Test4",
    "3",
    "124315"
  ],
  [
    "Test5",
    "5",
    "29509"
  ],
  [
    "Test6",
    "7",
    "47742"
  ],
  [
    "Test7",
    "2",
    "231034"
  ]
]

我只需要数组数组中的前两个索引 例如:

[["Test1","4"],["Test2","6"],["Test3","1"],["Test4","3"],["Test5","5"],["Test6","7"],["Test7","2"]]

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 你可能想在每个元素上 map slice
  • @BrianMcCutchon:切片和拼接
  • array.slice(0,2)。使用这个

标签: javascript arrays angular typescript


【解决方案1】:

let array=[
  [
    "Test1",
    "4",
    "160496"
  ],
  [
    "Test2",
    "6",
    "38355"
  ],
  [
    "Test3",
    "1",
    "1221781"
  ],
  [
    "Test4",
    "3",
    "124315"
  ],
  [
    "Test5",
    "5",
    "29509"
  ],
  [
    "Test6",
    "7",
    "47742"
  ],
  [
    "Test7",
    "2",
    "231034"
  ]
];

array.forEach(x=>
  (x.splice((x.length-1), 1))?x:false
);
 console.log(array);

【讨论】:

  • array.map反正创建了一个新数组,那我们为什么要干扰原始数组呢?还有为什么这个答案在没有任何评论的情况下被否决了?有什么理由吗?
  • @Nitheesh 您可能用第一个问题回答了最后两个问题。
  • @VLAZ 对不起?没听懂
  • @Nitheesh 你的最后两个问题是“为什么这个答案在没有任何评论的情况下被否决?有什么理由吗?”我认为答案是你的第一个问题:“array.map 无论如何都会创建一个新数组,那我们为什么要干扰原始数组呢?"
【解决方案2】:

使用array.map 从现有数组生成新数组的托盘

const array = [
  ["Test1", "4", "160496"],
  ["Test2", "6", "38355"],
  ["Test3", "1", "1221781"],
  ["Test4", "3", "124315"],
  ["Test5", "5", "29509"],
  ["Test6", "7", "47742"],
  ["Test7", "2", "231034"]
];
const newArray = array.map(item => [item[0], item[1]]);
console.log(newArray);

【讨论】:

    【解决方案3】:

    我假设您不想更改原始 array 变量并且只想删除最后一个索引,无论内部数组有多长,以下解决方案可能会有所帮助。

    let array=[
      [
        "Test1",
        "4",
        "160496"
      ],
      [
        "Test2",
        "6",
        "38355"
      ],
      [
        "Test3",
        "1",
        "1221781"
      ],
      [
        "Test4",
        "3",
        "124315"
      ],
      [
        "Test5",
        "5",
        "29509"
      ],
      [
        "Test6",
        "7",
        "47742"
      ],
      [
        "Test7",
        "2",
        "231034"
      ]
    ]
    
    const newArray = array.map(innerArray => innerArray.slice(0, -1));
    
    console.log(newArray);

    【讨论】:

      【解决方案4】:

      这将遍历您的数组并删除每个嵌套数组的最后一个元素

      for (let nestedArray of array) {
          let lastIndex = nestedArray.length - 1
          nestedArray.splice(lastIndex, 1)
      }
      

      在此处了解拼接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

      【讨论】:

        猜你喜欢
        • 2014-02-08
        • 2021-11-09
        • 2020-09-08
        • 2012-11-25
        • 1970-01-01
        • 2019-07-23
        • 2018-10-23
        • 1970-01-01
        • 2020-03-02
        相关资源
        最近更新 更多