Compare two arrays, get unusual values

I have a simple problem that is hard for me to think about:

var oldValues : Array = [ 4, 5, 6 ]; var newValues : Array = [ 3, 4, 6, 7 ]; 
  • I want to get values ​​from newValues ​​that are not in oldValues ​​- 3, 7
  • I want to get values ​​from oldValues ​​that are not in newValues ​​- 5
  • A way to get both sets of values ​​together would be nice - 3, 5, 7

I can only think of intricate methods for each using nested loops that do a lot of redundant checks. Can anyone suggest something cleaner? Thanks.

+4
source share
3 answers

You need a bunch of loops, but you can optimize them and completely avoid nested loops with a search 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 is not new: 5

new not old: 3.7

+3
source
 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
source

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

  • clone the list and use newValues.removeItems (oldValues) to get values ​​from newValues ​​that are not in oldValue

  • and then use the same way to get values ​​from oldValues ​​that are not in newValue

  • execute the previous two results

Your code will not have loops ... Although inside the code of the list class there will be a loop: D

0
source

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


All Articles