OzW OzW - 2 years ago 172
AngularJS Question

splice does not remove element from array


Well, this is indeed embarrassing. Thank you all for noticing the type, I would have deleted this question, but I can't (because it has answers). Let this be a monument.

I'm trying to write an app which, given an object and an array, removes the object from the array (if it exists), or adds it to the array (if it does not exist).

Initial array:

var permissions = [{
id: 3,
name: "Perm3"
}, {
id: 1,
name: "Perm1"

Add\remove function:

triggerPermission = function(perm) {
var idx = permissions.indexOfById(perm);
if (idx === -1) {
} else {
permissions.slice(idx, 1); //should have been SPLICE...

helper function:

Array.prototype.indexOfById = function(obj) {
var idx = -1;
for (var i = 0; i < this.length; i++) {
if (this[i].id === obj.id) {
idx = i;
return idx;

As can be seen on the plunkr, I'm trying to use this in an AngularJS app, with checkboxes as triggers. Some permissions are getting returned by
(but the permissions array is not being changed), and some are not even getting returned. What am I missing here?

Answer Source

Your code uses slice, not splice.

slice does not modify the array, it returns a modified copy.

splice is the method you are after, which modifies the array in-place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download