ActionScript实现数组快速去重算法
今天在写flex时遇到了,需要过滤数组中重复数据的问题,查询后发现,flex没有java中set这样的集合,可以用来直接去重。
就简单的写了个快速去重算法,测试了一下,速度挺快的。我array里是String类型,如果类型是其它的,替换String就行了。肚子饿的很,今天不加班了。。早早的回吧。
/** * Created with IntelliJ IDEA. * User: DongYang * Date: 13-3-25 * Time: 下午7:46 * Progress every day a little more. */ package com.skycloud.nettopo.util { public class DataUtil { public static function filterRepeat(array:Array):Array{ array.forEach(function (str:String, i:int, a:Array):void { //我这里array里的元素为String类型 if (array.length != rr(array, str).length) { array = rr(array, str); array = filterRepeat(array); } }); return array; function rr(lines:Array, str:String):Array { lines = lines.filter(function (ss:String, ii:int, aa:Array):Boolean{ return ss != str; }); lines = lines.concat(str); return lines; } } } }
2013.5.3 新增两种去重算法。
public static function removedDuplicates1(oldArray:Array):Array{ var keys:Object = {}; var key:Dictionary=new Dictionary(); var newArray:Array=oldArray.filter(function(item:Object,index:uint,array):Boolean{ if (keys.hasOwnProperty(String(item))) { return false; } else { keys[item] = item; return true; } }); return newArray; } public static function removedDuplicates2(oldArray:Array):Array{ var keys:Dictionary=new Dictionary(); var newArray:Array=oldArray.filter(function(item:String,index:uint,array):Boolean{ if (keys[item]==item) { return false; } else { keys[item] = item; return true; } }); return newArray; }