-1

I am trying to remove all the items from a list except "Red" on a specific condition by using remove(), but when I debug, it gives error:

"Accessing the 'arguments' property of a function is not allowed in strict mode".

Is there a alternative for remove that I can use in this situation. Below is the code that I am using:

for (var k = 0; k < homeCtrl.List.length; k++) {
      if (homeCtrl.ColorList[k].name != 'Red') {
            homeCtrl.ColorList.remove[k];
      }
}
Programmermid
  • 439
  • 2
  • 7
  • 21

3 Answers3

1

Since you want to remove items from an array, you can simply use Array.prototype.filter():

var array = [  
   {  
      "id":1,
      "name":"Red"
   },
   {  
      "id":2,
      "name":"Blue"
   },
   {  
      "id":3,
      "name":"Red"
   },
   {  
      "id":4,
      "name":"Green"
   },
   {  
      "id":5,
      "name":"Red"
   }
];

var withoutRed = array.filter(function(value) {
  return value.name != "Red";
});

console.log(withoutRed);
developer033
  • 20,983
  • 7
  • 64
  • 95
0

You can use splice()

for (var k = 0; k < homeCtrl.List.length; k++) {
    if (homeCtrl.ColorList[k].name != 'Red') {
        homeCtrl.ColorList.splice(k, 1);
    }
}

See a dummy example below:

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {

  var homeCtrl = this;
  homeCtrl.List = [{
    name: 'Yello'
  }, {
    name: 'Red'
  }, {
    name: 'green'
  }];
  
  homeCtrl.ColorList = angular.copy(homeCtrl.List);

  homeCtrl.remove = function() {
    for (var k = 0; k < homeCtrl.List.length; k++) {
      if (homeCtrl.ColorList[k] && homeCtrl.ColorList[k].name != 'Red') {
        homeCtrl.ColorList.splice(k, 1);
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController as fooCtrl">
  
  {{fooCtrl.ColorList}}
  <br><br>
  <a ng-click="fooCtrl.remove()" href="">Clear</a>
</div>
Shashank Agrawal
  • 21,660
  • 9
  • 71
  • 105
-2

It looks like you're coming across issues here because you're modifying the list that you're iterating over. Javascript doesn't like this. Try creating a new list instead, and then replacing the old one.

var myNewList = [];
for (var k = 0; k < homeCtrl.List.length; k++) {
                    if (homeCtrl.List[k].name === 'Red') {
                        myNewList.push(homeCtrl.List[k]);
                    }
// now myNewList only contains the 'Red' elements.
timje
  • 273
  • 2
  • 11