2

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?

rrk
  • 14,861
  • 4
  • 25
  • 41
TechGuy
  • 3,559
  • 12
  • 46
  • 71
  • 1
    i think this [doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) will help you.. – sharma sk Apr 12 '16 at 05:49
  • Duplicates: [Remove item from array by value](http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value) and [Remove a particular element from an array in JavaScript?](http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript) and 500 more. – Roberto Apr 12 '16 at 05:57

5 Answers5

1

Your jSON structure should not contain = instead it should be in key:value pair.You can filter this by using grep fun


    var data= [ 
     { NewsType:"WORLD NEWS",  NoOfHours:2},
     { NewsType:"LOCAL NEWS",  NoOfHours:1},
     { NewsType:"SPORTS NEWS",  NoOfHours:2}
    ]

    var target = "WORLD NEWS";
    data = jQuery.grep(data, function(e){ 
         return e.NewsType != target; 
    });

Rahul Soni
  • 17
  • 4
0

try replacing

NewsArray.splice($.inArray(remItem, NewsArray), 1);

with

NewsArray = NewsArray.filter(function(val){return val.NewsType.indexOf(remItem)== -1});

This will filter out items which has WORLD in it.

gurvinder372
  • 61,170
  • 7
  • 61
  • 75
0

Reffer this link

var y = ['WORLD NEWS','LOCAL NEWS', 'SPORTS NEWS'] 
var removeItem = 'WORLD NEWS';
y = jQuery.grep(y, function(value) { 
return value != removeItem; 
});
GAMITG
  • 3,670
  • 7
  • 30
  • 50
0

Try using filter

var obj = [{ NewsType:"WORLD NEWS",  NoOfHours:2},{ NewsType:"LOCAL NEWS",  NoOfHours:1},{ NewsType:"SPORTS NEWS",  NoOfHours:2}];

var rez = obj.filter(function(v){
 return v.NewsType != "WORLD NEWS";
});
madalinivascu
  • 30,904
  • 4
  • 32
  • 50
0

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>
guest271314
  • 1
  • 10
  • 82
  • 156