开发者

Compare Two Arrays, Get Uncommon Values

开发者 https://www.devze.com 2022-12-17 02:29 出处:网络
I have a simple problem that I\'m having trouble thinking around: var oldValues : Array = [ 4, 5, 6 ];

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

var oldValues : Array = [ 4, 5, 6 ];
var开发者_C百科 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 methods for each by using nested loops that do a lot of redundant checking. Can someone suggest something more clean? Thanks.


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


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);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号