Skip to content
Advertisement

How to get index of object in array of objects and splice it?

I’m using angular 1.3, but his question maybe related only to javascript.

My candidates array:

var candidates = [
  { "attr1": "lu", "attr2": "pizza" },
  { "attr1": "gina", "attr2": "sushi" },
  { "attr1": "hed", "attr2": "hummus" }
];

My peoples array:

var peoples = [
  { "attr1": "bob", "attr2": "pizza" },
  { "attr1": "john", "attr2": "sushi" },
  { "attr1": "larry", "attr2": "hummus" }
];

And i’ve some checkbox too:

<div class="checkbox" ng-repeat="d in candidates ">
<label>
<input name="d[]" type="checkbox"ng-click="addRemove(d)" ng-value="d">
 {{d.attr1}}
</label>

So i’ve a function that toggles an item (from candidates) and I want to add or remove (if already exists)

 $scope.addRemove = function (item) {      
            var idx = peoples.indexOf(item);
            if (idx > -1) {             
                peoples.splice(idx, 1);
            }
            else {
                peoples.push(item);
            }         
        };

For some reason, if (idx > -1) its never true and it keeps add items even if they already exists.

Answer

indexOf will not compare object by value instead, it compare object by reference. You can do the following .

(Sorry updated my answer to get the “idx” and not if it exists )

You can do this :

var idx = peoples.map(function(p){ return p.attr2;}).indexOf(item.attr2);

if (idx) {             
            peoples.splice(idx, 1);
        }
        else {
            peoples.push(item);
        }
Advertisement