user3821206
user3821206

Reputation: 619

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:

enter image description here

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

Upvotes: 0

Views: 2889

Answers (2)

Unknown
Unknown

Reputation: 531

Try splicing in reverse order. i.e 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);
}

Upvotes: 2

YakovL
YakovL

Reputation: 8316

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.

Upvotes: 3

Related Questions