TechGuy TechGuy - 5 months ago 10
jQuery Question

Array contains doesn't capture

I have a array and array looks like this,I want to know about the is NewsType ="Int" included in the array.

array is NewsTypeArray.

When i debug in firebug.array looks like this,

0 Object { NewsType="Local"}
1 Object { NewsType="Int"}

var InternationalNewsfound = $.inArray("Int", NewsTypeArray) > -1;


But
InternationalNewsfound is shows me false.

Answer

Use a filter with jquery .grep(),

var NewsTypeArray = [{"NewsType": "Local"}, {"NewsType": "Int"}];

var InternationalNewsfound = $.grep(NewsTypeArray, function(obj) { 
                                 return obj.NewsType === "Int"; 
                             }).length > 0;
console.log(InternationalNewsfound);
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>

*Note : While just .length would help you check for truthiness you could still use .length > 0 for the flag.