0
var arr1= [];
var value = "value";

if ($.inArray(value, arr1) !== -1){
    //value found
}

To check for a value if it exist in array we use above code. What i need is to check a value from an array if it exist in another array. What i did is below. But i am not certain why i always get not found even if in the array there is a same value. Any suggestion is appreciated

FIDDLE

var arr1 = [{
    "id": "1"
}, {
    "id": "2"
}]
var arr2 = [{
    "id": "2"
}, {
    "id": "3"
}]
$.each(arr2, function (index, value) {
    console.log(value.id);
    if ($.inArray(value.id, arr1) !== -1) {
        alert('found');
    } else {
        alert('q');
    }
});
Brownman Revival
  • 3,620
  • 9
  • 31
  • 69
  • @arun i dont think it is a duplicate of the question you posted... My problem is i need to get every value from an array and check each value if it exist in another array. please clarify – Brownman Revival Aug 27 '15 at 07:11
  • http://jsfiddle.net/szb5gwf9/1/ $.inArray only works with arrays – eaCe Aug 27 '15 at 07:12
  • @eaCe thanks for that one but my array is dynamic and the way you check your array is like the example i posted above for checking array value from one array only..i need to check the value from 1 array if it exist in another array.. i hope i am not confusing anyone – Brownman Revival Aug 27 '15 at 07:14
  • 1
    http://jsfiddle.net/arunpjohny/ybjvyt7r/1/ - I marked it as a duplicate because the logic needed is the same – Arun P Johny Aug 27 '15 at 07:15
  • i see i wasnt able to understand what exactly the question you posted is about that is why i said it is not the same – Brownman Revival Aug 27 '15 at 07:24

1 Answers1

1

That's because your inner comparison compares the id value ("2", "3") with the objects inside arr1 (which are NOT the values "1" & "2").

Even if you did compare objects (value instead of value.id), it won't work. That's because of the defined equality (or rather lack of...) of objects.

When comparing objects in JavaScript, the comparison is reference based, not value based. Consider this:

alert({a:1} == {a:1})

The reason you don't see this problem with your first example is that string equality is value based.

In order to overcome this, you need to compare the values, or key-value pairs in your objects.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • please give me time to understand the answer thank you – Brownman Revival Aug 27 '15 at 07:24
  • @BrownmanRevival - By all means, take your time. – Amit Aug 27 '15 at 07:34
  • now i understand what you are trying to say is i am comparing `2 == "id": "1"` and `3 == "id": "2"` since i am comparing the value of 2 with regards to the element(and not the value which are 1 and 2 respectively) in the arr1.. Am i correct? – Brownman Revival Aug 27 '15 at 07:43
  • 1
    Yes, that's the first part of my answer and the "direct" reason your code isn't working. – Amit Aug 27 '15 at 07:51