简体   繁体   中英

How do I remove an array from an array?

Here is my array:

var myarray = [["d1", "sections/Dashboard-summary.html", "Dashboard"], 
               ["add", null, ""],
               ["20", "sections/MW-1-summary.html", "MW-1"],
               ["21", "sections/SB-5-summary.html", "SB-5"]]

How do I remove the second element ["add", null, ""] so that the new array is

[["d1", "sections/Dashboard-summary.html?781", "Dashboard"],
["20", "sections/MW-1-summary.html?903", "MW-1"],
["21", "sections/SB-5-summary.html?539", "SB-5"]]

That element might not always be in the second position but its first value will always be "add". How do I remove the array with the first value (myarray[1][0]) of "add"?

That element might not always be in the second position but its first value will always be "add". How do I remove the array with the first value (myarray[1][0]) of "add"?

Use a loop with splice() .

for (var i = 0, myarrayLength = myarray.length; i < myarrayLength; i++) {
    if (myarray[i][0] === 'add') {
        myarray.splice(i, 1);
        break;
    }
}

jsFiddle .

Use splice , like so:

myarray.splice(1, 1)

See this tutorial for more information on splice .

You can remove it completely (slow):

myarray.splice(1, 1);

You can delete it from the array, and left a "hole" in it (left the position 1 undefined):

delete myarray[1];

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