1

I am looking a way to delete all elements from array if target object attribute is present in array.

var msg={name:'tar', type:'SR'}; //want to delete all object with type=SR

  var items= [{name:'oh', type:'SR'},{name:'em', type:'PR'},
  {name:'ge', type:'MR'},{name:'ohoo', type:'SR'}];

    items.splice( items.indexOf(msg.type), 1 );

In this way only one object is deleting. Can someone suggest a better way that without using a loop i can delete all the target object from array

5
  • Are you trying to remove all elements from the array if at least one object contains a specific property with a specific value or are you trying to remove only the objects that have a specific property with a specific value? Commented Mar 24, 2016 at 13:16
  • 1
    Your code is deleting all objects except the last one, items.indexOf(msg.type) return -1 as indexOf look for the value "SR" Commented Mar 24, 2016 at 13:16
  • I am trying to delete all those objects which have type:'SR'. Commented Mar 24, 2016 at 13:20
  • Then you should clarify the first sentence in your question. Commented Mar 24, 2016 at 13:20
  • Sorry I already mentioned this in a code comment. Commented Mar 24, 2016 at 13:22

2 Answers 2

7

You can try something like following

items = items.filter(function(item){
     return item.type !== msg.type;
});
Sign up to request clarification or add additional context in comments.

Comments

2

a bit of functional and it's done:

var result = items.filter(function(item){
    return (item.type == msg.type) ? false : true;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.