-1

I am searching an array in jQuery,

var arr = ["mango","banana","jackfriut","apple","google"];
var removeItem = "google";   //works fine
var removeItem = "ogle";   //fails

arr = $.grep(arr, function(value) {
  return value != removeItem;
});
alert(arr)

When I am passing "google" then its working fine. Please let me know that it should work when I pass only some content like "ogle". its like wildcard.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Khusboo
  • 117
  • 1
  • 1
  • 9

2 Answers2

2

You can use indexOf for your condition

 var arr = ["mango","banana","jackfriut","apple","google"];
 var removeItem = "ogle";   //fails

 arr = $.grep(arr, function(value) {
    if(value.indexOf(removeItem) == -1)
       return value;
 });
 alert(arr)

JSFiddle

Hope it helps :)

Community
  • 1
  • 1
Arun AK
  • 4,353
  • 2
  • 23
  • 46
1

You can use jQUery's built in $.inArray function.

var arr = ["mango","banana","jackfriut","apple","google"];

function inArray() {
    if($.inArray(value, arrayName) !== -1) {
        alert("Value is in array");
    } else {
        alert("Value is not in array");
    }
}

You can then call your function passing in the value you are looking for:

inArray("google");

Of course, the logic you choose to return in the function is up to you but this is the best way to check for values in an array.

midda25
  • 152
  • 1
  • 2
  • 12