Deleting a column from a multidimensional array in javascript

前端 未结 6 1296
遥遥无期
遥遥无期 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 00:51

    Iterate through the array and splice each sub array:

    var idx = 2;
    for(var i = 0 ; i < array.length ; i++)
    {
       array[i].splice(idx,1);
    }
    

    JSFiddle.

    Edit: I see you don't want to use splice due to out-of-bounds problems and array length changing. So:

    1.You can check if you're out of bounds and skip the slice.
    2.You can create an array of indexes you want to delete and simply create new arrays from the indexes that don't appear in that array (instead of deleting, create new arrays with the opposite condition).

    Something like this:

    var array = [
        ["a", "b", "c"],
        ["a", "b", "c"],
        ["a", "b", "c"]
    ];
    
    var idxToDelete = [0,2];
    
    for (var i = 0; i < array.length; i++) {
        var temp = array[i];
        array[i] = [];
        for(var j = 0 ; j < temp.length ; j++){
            if(idxToDelete.indexOf(j) == -1) // dont delete
            {
                array[i].push(temp[j]);
            }
        }
    }
    

    New JSFiddle.

提交回复
热议问题