views:

913

answers:

3

I have a simple problem that I'm having trouble thinking around:

var oldValues : Array = [ 4, 5, 6 ];
var newValues : Array = [ 3, 4, 6, 7 ];
  1. I want to get the values from newValues that aren't in oldValues - 3, 7
  2. I want to get the values from oldValues that aren't in newValues - 5
  3. A way of getting both sets of values together would be nice as well - 3, 5, 7

I can only think of convoluted for each...in nests that do a lot of redundant checking. Cany someone suggest something more clear? Thanks.

A: 

You need a bunch of loops, but you can optimize them and totally avoid nested loops by using a lookup object.

var oldValues : Array = [ 4, 5, 6 ];
var newValues : Array = [ 3, 4, 6, 7 ];

var oldNotInNew:Array = new Array();
var newNotInOld:Array = new Array();

var oldLookup:Object = new Object();

var i:int;

for each(i in oldValues) {
    oldLookup[i] = true;
}       

for each(i in newValues) {
    if (oldLookup[i]) {
        delete oldLookup[i];
    }
    else {
        newNotInOld.push(i);
    }
}

for(var k:String in oldLookup) {
    oldNotInNew.push(parseInt(k));
}

trace("Old not in new: " + oldNotInNew);
trace("new not in old: " + newNotInOld);

Results:

Old not in new: 5

new not in old: 3,7

Sam
That's working pretty well for me. I was thinking about a look-up table, but was distracted from that thought. Thanks for this.
grey
A: 

use casa lib

main page:http://casalib.org/

doc: http://as3.casalib.org/docs/

list class: http://as3.casalib.org/docs/org_casalib_collection_List.html

removeItems http://as3.casalib.org/docs/org_casalib_collection_List.html#removeItems

  1. clone the list, and use newValues.removeItems(oldValues) to get the values from newValues that aren't in oldValue

  2. and then use the same way to get the values from oldValues that aren't in newValue

  3. concat the previous two results

There will be no looping in your code... Although there will be looping inside the code of list class :D

Unreality
Thanks for the info, but personally I'd like to avoid relying on a library for the functionality for this project. Might come in use later.
grey
A: 
var difference : Array = new Array();
var i : int;
for (i = 0; i < newValues.length; i++)
    if (oldValues.indexOf(newValues[i]) == -1)
        difference.push(newValues[i])
trace(difference);
jaredy