2

Is there a quicker way besides iterating thru all entries in the associative array

Related to - How do I delete a value from an Object-based associative array in Flex 3?

2
  • 1
    What's wrong with the solution posted on the linked thread? If you know the property you used as the key for the associative array just delete myArray["myKey"]? Commented Jan 7, 2011 at 18:40
  • ah gotcha, yes as posted below you can just set the array to null then re-instantiate it I believe the GC will be able to collect it then, from what I've read on this you can force the gc to collect but it's generally best not to and to just signal the freeing of the memory by setting to null. Commented Jan 7, 2011 at 18:53

2 Answers 2

3

There are a few solutions to clear an associative array (which is the same as a dynamic object):

  1. The quickest one is assigning a new array. In most cases this will be the preferred solution.

    myArray = [];

  2. Removing all keys from the array. It will have the same effect as solution one. However, the array instance stays the same.

    for (var key:String in myArray)
        delete myArray[key];

  3. Setting all values in the array to null. The array instance will stay the same and all of it's keys are preserved. Only the array's values are set to null.

    for (var key:String in myArray)
        myArray[key] = null;

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

Comments

0

I think myArray = null; should remove the whole bunch.

UPDATE

var i:int=-1;
for(;myArray[++i];)
{
    delete myArray[i];
    myArray[i] = null;
}

OR

for(var r:String in myArray)
{
    delete myArray[i];
    myArray[r] = null;
}

7 Comments

What if I want to reuse the object? Assigning null would imply I have to create a new Object. All I want is to clear the entries.
Yep thats what I have done currently, but wanted to know if there's a better way
myArray[r] = null; doesn't work. You have to use delete myArray[r]; otherwise the index won't be removed from the array.
Thanks for editing your answer. However, if I understand Nitin correctly, he wants to completly remove all entries from the array. So, the myArray[r] = null; should be omitted. You are currently deleting and adding back a new entry with the value null.
I think you are right. As Nitin said he wants to keep the Object for reusing so setting the values to null should be fine, and this case we don't need delete the values. In another case if you want to totally remove everything you have to delete the whole array. Am I wrong in that?
|

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.