Search code examples
javascripthtmlangularjsloopslodash

Compute the newly pushed data in array using loop


I am having trouble in proper calculation of numerical values in an array inside a loop.

Scenario

  • The tbody generates a list of dynamic values.
  • The button inside td has a function called preBookThis() with params.
  • When the User clicks the button, it will trigger the function then push the data into an array variable.
  • Upon pushing, there will be a for loop that will iterate and compute the values. ($scope.nights is the two dates - ie. 2018-05-05 and 2018-05-07, so it will have a value of 2)

The problem

  • Lets imagine that there were three rows in the tbody and have the following values.

    $scope.nights = 2; row1 = 100; row2 = 200; row3 = 300;

  • When the user clicks the button in row 1 the computation works and performs as expected

    amount_row1 = 200;

but...

  • When the user clicks the button in row 2, the computed values of the first row will be doubled.

    amount_row1 = 400; amount_row2 = 400;

and also...

  • When the user clicks the button in row 3, the computed values of the first row and second row will be doubled again.

    amount_row1 = 800; amount_row2 = 800; amount_row3 = 600;

The final output should be:

 amount_row1 = 200;
 amount_row2 = 400;
 amount_row3 = 600;

HTML

<tbody ng-repeat="room in roomsDisplay">
    <tr>
        <td>
            <div class="col-md-6"><img ng-src="images/rooms/{{room.room_image}}"></div>         
        </td>
        <td>
            <div style="margin-top: 20px;"><input type="button" 
                ng-click="preBookthis({room})" class="btn btn-primary" 
                value="Book this Room"></div>
        </td>
    </tr>
</tbody>

JS

$scope.preBookthis = function(data){
    $scope.totalAmount = 0;
    $scope.bookData.push({ 
        'room_name': data.room.room_name, 
        'price': data.room.price,
        'amount': $scope.amount,
        'id' : data.room.rooms_type_id
    });

    _.forEach($scope.bookData, function(value, key){
        value.amount = value.amount * $scope.nights;
    });
}

Solution

  • Do the calculations only once when you add the new object and don't loop over all the others that have had it calculated already

    Something like:

    $scope.preBookthis = function(data){
        $scope.totalAmount = 0;
        $scope.bookData.push({ 
            'room_name': data.room.room_name, 
            'price': data.room.price,
            'amount': $scope.amount * $scope.nights,// calculate only for this item
            'id' : data.room.rooms_type_id
        });  
    }