简体   繁体   中英

Removing a specific element from each array in a 2D array

I am trying to remove the 3rd element from each array with the array.

What I have:

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"]]

What I need:

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

I have assumed using splice but can not think how I would use it with a 2d array.

Use splice on each subarray.

 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) 

Edit: to keep the original data intact, you'd need to copy the arrays prior to splicing.

 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) 

You can use the following code snippet

 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); 

You can use .map() with .splice() .

  • .map() creates a new array with values returning from callback function.
  • .splice() removes one or more elements from the array.

Demo:

 let 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"] ]; let removeIndex = (array, index) => array.map(a => (a.splice(index, 1), a)); console.log(removeIndex(data, 2)); 

Docs:

you can use splice supplying the index of the index you want to remove in this case 2 and 1 if you want to remove only one element.

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.forEach( arr => {
// loop over all arrays to get the individual ones. 
  arr.splice(2 , 1) // then call splice. 
})

console.log(data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM