Programmermid Programmermid - 4 months ago 15
Javascript Question

Alternative for remove() when using strict mode, filter using one element and hiding all other

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];
}
}

Answer

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);

Comments