Question

Good afternoon.

I need to check if the item already exists before add in an dataprovider. But the indexOf method always return -1 wheen i try to do this check in my array. Anyone who can help me? Thank you.

var contacts:Array = new Array();

for each(var i:Object in windowAddContact.selectedContacts)  {

  if(contacts.indexOf(i) == -1) {

    contacts.push(i);               
  }
}

contactList.dataProvider = contacts;                            
Was it helpful?

Solution

Given the code; you've provided; I wouldn't expect indexOf to return anything but -1; unless youhave multiple instances of the same object in windowAddContact.selectedContacts; which is possible but seems unlikely.

The contacts array starts out empty and all this code does is copy items from a collection into an Array. Try this:

var contacts:Array = new Array();
contacts.add(windowAddContact.selectedContacts[0]);
for each(var i:Object in windowAddContact.selectedContacts)  {

  if(contacts.indexOf(i) == -1) {

    contacts.push(i);               
  }
}

And I'll bet you'll see indexOf(i) return something other than -1 once. I'm unclear what you're trying to do, though. Why is the loop necessary? Can't you just do:

contactList.dataProvider = windowAddContact.selectedContacts; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top