0

The function toggleIntervention is called every time a check-box is checked/unchecked. It should push an object to array or remove it from the array depending if its checked/unchecked.

I am using indexOf to check if the object exist in the array, however the index is always -1 even if the object exists in the array. What am I missing?

    $scope.selectedInterventions=[];
    $scope.toggleIntervention = function(inputIntervention) {

        var intervention =  {
                cptCode:inputIntervention.service,
            description:inputIntervention.description,
                  notes:"intervention notes",
             targetDate:"11/11/2014",
         resolutionDate:"11/11/2014"
        };

        // The index always -1 even if the object exists in the array of selectedInterventions
        var idx = $scope.selectedInterventions.indexOf(intervention); 
        if (idx > -1) { 
            $scope.selectedInterventions.splice(idx, 1);
        } else {
            $scope.selectedInterventions.push(intervention);
        }
    };
Himalay Majumdar
  • 3,883
  • 14
  • 65
  • 94
  • 6
    `indexOf` will be looking for a matching object *reference*. You can't create a brand new `intervention` object and find a matching one (even though its properties are identical). – Cᴏʀʏ Nov 05 '14 at 18:24
  • Yep, use something like underscore's `find` and then splice that element. – Mohammad Sepahvand Nov 05 '14 at 18:26
  • 3
    You'll need to loop through the `selectedInterventions` array and [compare each object for equality](https://docs.angularjs.org/api/ng/function/angular.equals). – Blazemonger Nov 05 '14 at 18:26
  • Thank you Cory for clarifying, is there a standard way to check object equality in javascript? – Himalay Majumdar Nov 05 '14 at 18:26
  • @Cory is right, why don't you use the **[`$filter` filter](https://docs.angularjs.org/api/ng/filter/filter)** instead? – Josep Nov 05 '14 at 18:26
  • Thank you guys, I will try the above approaches and let you know. – Himalay Majumdar Nov 05 '14 at 18:26
  • Related: [indexOf method in an object array?](http://stackoverflow.com/questions/8668174/indexof-method-in-an-object-array) – apsillers Nov 05 '14 at 18:30
  • @Blazemonger solutions worked for me, i can post my answer if the duplicate is removed, since now the question is Angular specific. Thanks all!. – Himalay Majumdar Nov 05 '14 at 20:30

0 Answers0