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??
Just call the splice(4, 1)
method, when 4 is row number and 1 is number of rows to remove -
twoDimensionalArray.splice(4, 1); // remove 4th row
Also shift()
and pop()
are very handy methods which remove first and last rows accordingly -
twoDimensionalArray.shift(); // to remove first row
twoDimensionalArray.pop(); // to remove last row
Here's an example of how to remove a row by 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 ] ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With