简体   繁体   中英

removing empty rows from an array in javascript

I have an array with empty rows,I have the field "codeOperation" to test if a row is empty or not,this is my table:

在此处输入图片说明

The client should fill the table whith data and left the rest of rows empty, what I want is when the client click on the "ADD" boutton only the data will be send and the emoty rows will be deleted.

this is my code:

//function to send the Data
$scope.updateGamme= function(gamme) {

    gamme.listElementGammeOf = $scope.finalOperationsList;

    $scope.DeleteEmptyRows(gamme.listElementGammeOf);

             $http
                 .put(
                     baseUrl +
                     "/gamme/update",
                     gamme)
                 .success(
                     function(gammeModifiee) {
                         //send the Data and update 
                            .....     
                     }); }

//delete the empty rows
$scope.DeleteEmptyRows = function(listelements){
            for (var i = 0; i < listelements.length; i++) {
                if (listelements[i].operationCode == "")
                    listelements.splice(i, 1);
            }

What I get as a result with this code, is that per example I get 5 items, my code will remove the rows 3 and 4 the row 2 is not deleted

Is there any problem with my code? Please help me find it.

Thanks for help

Looks like

for (var i = 0; i < listelements.length; i++) {
    if (listelements[i].operationCode == "")
        listelements.splice(i, 1);
}

should be

for (var i = 0; i < listelements.length; i++) {
    if (listelements[i].operationCode == "")
        listelements.splice(i--, 1);
}

When you iterate and remove items from an array, you should decrement your index not to miss an item after the index shift due to removing.

Try splicing in reverse order. ie remove rows from the last one.
I haven't tried your code but it must work.

 $scope.DeleteEmptyRows = function(listelements){
        for (var i = listelements.length-1; i >=0; i--) {
            if (listelements[i].operationCode == "") {
                listelements.splice(i, 1);
                         }
                   }
  }

The example I tried is...

var array = ["1","2","","",""];  
for(var i=array.length-1;i>=0;i--)
{
    if(array[i]=="")
       array.splice(i,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