How to remove row in 2d array in javascript

后端 未结 6 1644
醉梦人生
醉梦人生 2021-02-05 19:42

How to remove row in two dimensional array in JavaScript with row number. If I want to delete all elements in row number 4 then how can do it??

6条回答
  •  梦谈多话
    2021-02-05 20:24

    I realize this question is old, but it is one of the first results when searching for how to remove from a 2d (multidimensional) array in JS.

    Here is what I used to delete the inner array based on a key of the inner array. It should continue to work if there were multiple instances of the same key. In this example, I am searching for, and removing the array with the key of 18.

    Sorry about the formatting - it gets the point across.

    var items = [
      ["19", 1],
      ["18", 2],
      ["20", 3]
    ];
    
    //console.log(items);
    document.getElementById("a").innerHTML = items;
    
    for (var i = 0; i < items.length; i++) {
      if (items[i][0] == "18") {
        items.splice(i, 1);
      }
    }
    
    //console.log(items);
    document.getElementById("b").innerHTML = items;

    Before

    After

提交回复
热议问题