Search code examples
javascriptarrayswebsplice

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.


Solution

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