Better way to remove item from the array

I have a jquery array.In here i want to remove WORLD NEWS item. My array comes like this,

[Object { NewsType="WORLD NEWS",  NoOfHours=2},
Object { NewsType="LOCAL NEWS",  NoOfHours=1},
Object { NewsType="SPORTS NEWS",  NoOfHours=2}]

i have tried it like this,

var remItem ="WORLD" ;
NewsArray.splice($.inArray(remItem, NewsArray), 1);

but in here i hardcoded news,it's not good because sometimes it comes as a world or global or any other similar name.

How do i solve this problem?

Answers 1

  • You can use Array.prototype.indexOf(), $.grep()

    arr.splice(arr.indexOf($.grep(arr, function(obj) {
      return obj.NewsType === "WORLD NEWS"
    })[0]), 1);
    

        var arr = [{
          NewsType: "WORLD NEWS",
          NoOfHours: 2
        }, {
          NewsType: "LOCAL NEWS",
          NoOfHours: 1
        }, {
          NewsType: "SPORTS NEWS",
          NoOfHours: 2
        }];
    
         arr.splice(arr.indexOf($.grep(arr, function(obj) {
          return obj.NewsType === "WORLD NEWS"
        })[0]), 1);
      
        console.log(JSON.stringify(arr, null, 2))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>


Related Articles