Compare Two Arrays, Get Uncommon Values

自闭症网瘾萝莉.ら 提交于 2019-12-12 08:13:58

问题


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 methods for each by using nested loops that do a lot of redundant checking. Can someone suggest something more clean? Thanks.


回答1:


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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/2121994/compare-two-arrays-get-uncommon-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!