How to delete a string in a 2d array in javascript

How to delete a string in a two-dimensional array in JavaScript with a row number. If I want to delete all the items in line number 4, then how do I do this?

+11
javascript multidimensional-array delete-row
source share
6 answers

Here is an example of how to delete a row using splice :

 var array = []; var count = 0; for (var row=0; row<4; row++) { array[row] = []; for (var col=0; col<5; col++) { array[row][col] = count++; } } console.log(array); [ [ 0, 1, 2, 3, 4 ], [ 5, 6, 7, 8, 9 ], [ 10, 11, 12, 13, 14 ], [ 15, 16, 17, 18, 19 ] ] function deleteRow(arr, row) { arr = arr.slice(0); // make copy arr.splice(row - 1, 1); return arr; } console.log(deleteRow(array, 4)); [ [ 0, 1, 2, 3, 4 ], [ 5, 6, 7, 8, 9 ], [ 10, 11, 12, 13, 14 ] ] 
+10
source share

Suppose you have an array of 'arr', then you can delete the full string arr.splice(3,1) ;

+5
source share

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

Here is what I used to remove the internal array based on the key of the internal array. It should continue to work if there are multiple instances of the same key. In this example, I search and delete an array with a key of 18.

Sorry for the formatting - it gets the point.

 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; 
 <p>Before</p> <div id='a'></div> <p>After</p> <div id='b'></div> 
+2
source share

Here you have a good example of a two-dimensional array with a delete row button (delete by ID) + jQuery table preview. I hope this can be helpful!

JS DELETE ROW from Bidimensional ARRAY + Show on jQuery Cart Table https://jsbin.com/xeqixi/edit?html,js,output

+1
source share

Just call splice(4, 1) , when 4 is the line number and 1 is the number of lines to delete -

 twoDimensionalArray.splice(4, 1); // remove 4th row 

Also shift() and pop() are very convenient methods that respectively delete the first and last lines -

 twoDimensionalArray.shift(); // to remove first row twoDimensionalArray.pop(); // to remove last row 
0
source share

delete array [index]; Array length-- ;.

In your case, specify the index as 4 and execute the above statement, and you need to manually reduce the length of the array.

0
source share

All Articles