1

Short query is, in below piece of code why it's not printing found?

var products = [];
products.push("ABC", "XYZ");
var compareProducts = ["ABC","XYZ"];

console.log(products)


  if($.inArray(products, compareProducts) > -1)
    {
    alert("found"); 
  }
  else{
    alert("not found");
  }
3
  • 1
    What are u trying to do. The syntax is $.inArray(needle, haystack); You are providing both paramerters as array. Commented Dec 7, 2015 at 6:28
  • First parameter is supposed to be a value not the array itself.. go thorugh the .inArray API Commented Dec 7, 2015 at 6:29
  • got it guys my bad... Thanks for help... Commented Dec 7, 2015 at 6:32

3 Answers 3

3

According to documentation,

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

That's exactly how it works:

inArray: function( elem, arr, i ) {
    return arr == null ? -1 : indexOf.call( arr, elem, i );
}

It finds the occurcence of your elem in arr. It does not find the occurence of obejcts of an array in another array.

If you want to check that all items in products exist in compareProducts, you may iterate over the array or use Array.prototype.every:

var products = [];
products.push("ABC", "XYZ");

var compareProducts = ["ABC","XYZ"];

if (products.every(function(x) { return $.inArray(x, compareProducts) > -1; }))
{
    alert("found"); 
} else {
    alert("not found");
}
Sign up to request clarification or add additional context in comments.

1 Comment

The products.every will only determine if all products are in compareProducts.
2

The parameters to the inArray function is (String, Array) and not (Array, Array) in your case. Iterate over products and match each value using inArray

1 Comment

Beat me to it. Try: if($.inArray(products[0], compareProducts) > -1)
0

inArray is used to find the index of any single value, not multiple values . you are searching for an array in an array which is not meant for inArray.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.