从2D数组中的每个数组中删除特定元素

时间:2018-04-19 16:45:43

标签: javascript arrays web splice

我试图用数组从每个数组中删除第3个元素。

我有什么:

data =
[["51.9435","-4.26697","450","125"],
["51.9437","-4.26717","450","125"],
["51.9438","-4.26733","450","125"],
["51.944","-4.26748","450","125"]]

我需要什么:

data =
[["51.9435","-4.26697","125"],
["51.9437","-4.26717","125"],
["51.9438","-4.26733","125"],
["51.944","-4.26748","125"]]

我假设使用拼接,但我想不出如何将它用于2d数组。

4 个答案:

答案 0 :(得分:2)

在每个子阵列上使用splice

const data = [["51.9435","-4.26697","450","125"],
              ["51.9437","-4.26717","450","125"],
              ["51.9438","-4.26733","450","125"],
              ["51.944","-4.26748","450","125"]]

for( const array of data )
   array.splice(2, 1)
   
console.log(data)

编辑:为了保持原始数据的完整性,您需要在拼接之前复制数组。

const data = [["51.9435","-4.26697","450","125"],
              ["51.9437","-4.26717","450","125"],
              ["51.9438","-4.26733","450","125"],
              ["51.944","-4.26748","450","125"]]

const converted = data.map(function(array){
   const copy = array.slice()
   copy.splice(2, 1)
   return copy
})

console.log(data)
console.log(converted)

答案 1 :(得分:0)

您可以使用以下代码段



data =[["51.9435","-4.26697","450","125"],
       ["51.9437","-4.26717","450","125"],
       ["51.9438","-4.26733","450","125"],
       ["51.944","-4.26748","450","125"]];
data.map( (arr) => {arr.splice(2,1);});
console.log(data);




答案 2 :(得分:0)

您可以将<html> <body> <div id="move"></div> </body> </html>.map()一起使用。

  • .splice()创建一个新数组,其值从回调函数返回。
  • .map()从数组中删除一个或多个元素。

<强>演示:

.splice()

<强>文档:

答案 3 :(得分:0)

如果您只想删除一个元素,则可以使用mObsInt.set(mObsInt.get()+1); 提供您要删除的索引的索引splice2

1