Deleting a column from a multidimensional array in javascript

前端 未结 6 1307
遥遥无期
遥遥无期 2020-12-06 00:20

I have a 2D array:

var array = [[\"a\", \"b\", \"c\"],[\"a\", \"b\", \"c\"],[\"a\", \"b\", \"c\"]]

I want to delete an entire column of thi

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 01:06

    Useful code snipped that creates an independent copy of an array

    use slice method inside map. Here is an example:

    let arrayA = ['a', 'b', 'c', 'd']
    
    let arrayB = arrayA.map((val) => {
          return val.slice()
    })
    
    arrayB[2] = 'Z';
    
    console.log('--------- Array A ---------')
    console.log(arrayA)
    
    console.log('--------- Array B ---------')
    console.log(arrayB)

    Note: In Angular 10, I used different methods to get an independent copy of an array but all failed. Here are some of them:

    arrayB.push(arrayA) // failed    
    arrayB = Object.create(arrayA) // failed    
    arrayB = arrayA.splice() // failed
    

    All failed methods were copying references along with data.

提交回复
热议问题