Is there a more efficient AS3 way to compare 2 arrays for additions, deletions, and updates?

I am wondering if there is a better way to approach this than my current solution ...

I have a list of items, then I get another list of items. I need to compare two lists and make a list of existing elements (for updating), a list that does not exist in the new list (for deletion) and a list of elements that do not exist in the old list (for adding).

Here is what I am doing now - basically creating a search object for testing if the element exists. Thanks for any advice.

            for each (itm in _oldItems)
        {
            _oldLookup[itm.itemNumber] = itm;
        }

        // Loop through items and check if they already exist in the 'old' list
        for each (itm in _items)
        {
            // If an item exists in the old list - push it for update
            if (_oldLookup[itm.itemNumber])
            {
                _itemsToUpdate.push(itm);
            }
            else // otherwise push it into the items to add
            {
                _itemsToAdd.push(itm);
            }

            // remove it from the lookup list - this will leave only
            // items for removal remaining in the lookup
            delete _oldLookup[itm.itemNumber];
        }

        // The items remaining in the lookup object have neither been added or updated - 
        // so they must be for removal  - add to list for removal
        for each (itm in _oldLookup)
        {
            _itemsToRemove.push(itm);
        }
+3
source share
2 answers

Array, O (n), , , Object, ( O (1), O (log n) , - ). , :

var array1 : Array = // ... first array
var array2 : Array = // ... second array

// Build up dictionary of items in array1
var array1_presence_dictionary : Object = new Object();
for each (var item : * in array1 ){
    array1_presence_dictionary[item] = item;
}

// Iterate over array2, constructing list of common and not common elements
var both : Array = new Array();
var only_in_array2 : Array = new Array();
for each (var item : * in array2 ){
      var key : String = String(item);
      if ( array1_presence_dictionary.hasOwnObject(key) ){
          both.push(item);
      }else{
          only_in_array2.push(item);
      }
}

, , Set, Object Dictionary. , ... , dict[item]=item;, del dict[item];.

0

, , , ( , ). , only_in_array1, array1_presence_dictionary - , . array1_presence_dictionary , array1_presence_dictionary[item] = item; array1_presence_dictionary[item.itemNumber] = true;

, , , , String, [Object Class_Of_Item] .. .

, . 3 , , , , , , , , item.status. .

0

Source: https://habr.com/ru/post/1740849/


All Articles