2

I have an array & a literal object like this

var arr = [{a: 1}, {a: 2}, {a: 3}];
var e1 = {a: 1};

I want to implement a function (ex: containsObject(e1, arr)) what should return true in this case.

Please teach me the way without overriding base classes like Array.prototype.indexof

4

4 Answers 4

2

Try this:

var arr = [{a: 1}, {a: 2}, {a: 3}];
var e1 = {a: 1};
for (var i=0; i<arr.length; i++) {
  var found = true;
  for (var key in e1) {
    if (e1[key] != arr[i][key]) {
      found = false;
      break;
    }
  }
  if (found) {
    alert('found at index ' + i);
    break;
  }
}

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

Comments

2
        var arr = [{a: 1}, {a: 2}, {a: 3}];
var e1 = {a: 1};
function containsObject(e1, arr) {
    var i;
    for (i = 0; i < arr.length; i++) {
        if (JSON.stringify(arr[i]) === JSON.stringify(e1)) {
            alert("we found it")
        }else{
            alert(JSON.stringify(e1)+"not equal to"+JSON.stringify(arr[i]))
        }
    }
}
containsObject(e1, arr)

if you don't mind compare them in string, use this way. JSON.stringify() convert object to json string, I think you expect compare them in human vision, then that is it.

I don't think the 2 different object can be compared.they are 2 instance from Object,

3 Comments

Thank Ma Yubo. We save a loop, but I can trust function JSON.stringify. Is there any case what will be wrong with JSON.stringify?
don't know yet, JSON.stringify should be able to use for any object
yes, I know function JSON.stringify. I just consider in what case, this way is wrong (not find yet). I prefer your way and use it, the jcubic's way is right. I thought about it, but I am afraid of 2 loop :) Thank again
0

This may Help you

function containsObject(e1, arr)
    {
      var k=false;
      ap=arr.filter(function(a){
      if(JSON.stringify(a) === JSON.stringify(e1))
      {k=true; 
       return(true);}
     });
    (k===true)?console.log("in array"):console.log("not in array");
    }
var arr = [{a: 1}, {a: 2}, {a: 3}];
var e1 = {a: 1};
containsObject(e1,arr);

Since array is not containing any method so we can use stringify to compare objects.

Comments

-2

This may help you.

function containsObject(e1, arr) {
    var i;
    for (i = 0; i < arr.length; i++) {
        if (arr[i] === e1) {
            return true;
        }
    }

    return false;
}

1 Comment

you cannot compare 2 literal object by operator ===

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.