0

I have created the following code http://jsfiddle.net/EbCUx/

var arr = [{a:1,b:2,c:3},{a:3,b:5,c:6}];
var a = arr[0];
alert(arr.indexOf(a));
var b = {a:1,b:2,c:3};
alert(arr.indexOf(b));

Why indexOf() returns -1 eventhough contents of a and b are same.. I know that a is a reference value ..Is that the cause...And can anybody explain me the exact reason?

2
  • Linking a fiddle is helpful, but please also include your code in the question, so that this page will stay useful if/when the fiddle expires. Commented May 3, 2012 at 20:00
  • because arrays are also objects, it also happen with them. I think you can modify this answer to make it work with objects Commented May 3, 2012 at 20:31

3 Answers 3

3

You are comparing 2 different objects that happen to have the same values inside, but they are still different objects from an equality perspective.

Your original code:

<script>
    var arr = [{a:1,b:2,c:3},{a:3,b:5,c:6}];
    var a = arr[0];
    alert(arr.indexOf(a));
    var b = {a:1,b:2,c:3};
    alert(arr.indexOf(b));
</script>

An updated version that shows how to get a match on the comparison.

<script>
    var b = {a:1,b:2,c:3};
    var arr = [b,{a:3,b:5,c:6}];
    var a = arr[0];
    alert(arr.indexOf(a));
    alert(arr.indexOf(b));
</script>

If you want to compare 2 different objects that happen to have the same values, you have to do so manually.

Sign up to request clarification or add additional context in comments.

Comments

3

From MDN:

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

Since no two objects are ever strictly equal, you can not use indexOf to search an array of objects, you must loop (or extend indexOf to loop if the elements of the array are objects)

Comments

1

Use this instead

add this code:

<script>
   Array.prototype.newIndexOf = function( item ) {
      var count = this.length;
      var j = 0;
      while (this[j++] !== item && j < count) {}
      return (j === count) ? -1 : j;
   }
</script>

indexOf is slow and no strict equal check.

http://jsperf.com/indexof-vs-equaling/2

1 Comment

indexOf actually uses a strict equality check!

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.