比较两个数组,获取稀有价值 [英] Compare Two Arrays, Get Uncommon Values
本文介绍了比较两个数组,获取稀有价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我无法想围绕一个简单的问题:
VAR oldValues:数组= [4,5,6]。
变种newValues:数组= [3,4,6,7]。
- 我想从newValues不在oldValues获取值 - 3,7
- 我想从oldValues不在newValues获取值 - 5
- 在获得两组值在一起将是很好的,以及的一种方式 - 3,5,7
我只能想错综复杂的方法为每个使用嵌套循环,做了很多冗余校验的。有人建议可以更多的东西干净吗?谢谢你。
解决方案
您需要一堆循环,但你可以对它们进行优化,并完全避免嵌套循环利用查找对象。
VAR oldValues:数组= [4,5,6]。
变种newValues:数组= [3,4,6,7]。
VAR oldNotInNew:阵列=新的Array();
VAR newNotInOld:阵列=新的Array();
VAR oldLookup:对象=新的对象();
变种我:INT;
每一个(我在oldValues){
oldLookup [我] =真;
}
每一个(我在newValues){
如果(oldLookup [I]){
删除oldLookup [I]
}
其他 {
newNotInOld.push(ⅰ);
}
}
对于(VAR K:字符串中oldLookup){
oldNotInNew.push(parseInt函数(K));
}
跟踪(旧的不去新的:+ oldNotInNew);
跟踪(新不老:+ newNotInOld);
结果:
旧的不去新的:5
新不老:3,7
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 ];
- I want to get the values from newValues that aren't in oldValues - 3, 7
- I want to get the values from oldValues that aren't in newValues - 5
- 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
这篇关于比较两个数组,获取稀有价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文