如何删除数组flex中的重复值?

时间:2013-12-13 15:30:24

标签: actionscript-3 flex

如何在as3中删除数组中的重复值?如果我有一个数组= [1,1,2,2,4,5] 我想将结果作为array = [1,2,4,5]

5 个答案:

答案 0 :(得分:3)

另一种选择是使用哈希映射/ Dictionary,如下所示:

import flash.utils.Dictionary;

var a:Array = ["Tom", "John", "Susan", "Marie", "Tom", "John", "Tom", "Eva"];
var b:Dictionary = new Dictionary(true);//has map/cannot have duplicate keys
var c:Array = [];//filtered/unique entries array
for(var i:int = 0; i < a.length; i++) b[a[i]] = i;//hash array entries
for(var key:String in b) c.push(key);//put them back into an array
b = null;//clear/release the hash map

trace(c);//traces: Tom Eva John Susan Marie 

答案 1 :(得分:0)

var a:Array = ["Tom", "John", "Susan", "Marie", "Tom", "John", "Tom", "Eva"];
a.sort();
var i:int = 0;
while(i < a.length) {
    while(i < a.length+1 && a[i] == a[i+1]) {
        a.splice(i, 1);
    }
    i++;
}

可以看出here

答案 2 :(得分:0)

尝试类似:

     var array:Array = [1,1,2,2,4,5];
     trace(array);
     trace(removeDuplicates(array));

     function removeDuplicates(inArray:Array):Array
     {
        return inArray.filter(removeDuplicatesFilter);
     }

     function removeDuplicatesFilter(e:*, i:int, inArray:Array):Boolean
     {
        return (i == 0) ? true : inArray.lastIndexOf(e, i - 1) == -1;
     }

另外,我建议你创建一个类,并将它们实现为静态方法,例如。

     public class ArrayUtils
     {
            public static function removeDuplicates(inArray:Array):Array
            {
                return inArray.filter(_removeDuplicatesFilter);
            }

             protected static function _removeDuplicatesFilter(e:*, i:int, inArray:Array):Boolean
            {
           return (i == 0) ? true : inArray.lastIndexOf(e, i - 1) == -1; 
            }
       }

也可以使用:

        var array:Array = [1,1,2,2,4,5];
        trace(ArrayUtils.removeDuplicates(array));

答案 3 :(得分:0)

使用Underscore.as!

https://github.com/amacdougall/underscore.as

import com.amacdougall.underscore.*;
_.uniq([1,1,2,2,4,5);
// 1,2,4,5

答案 4 :(得分:0)

private function removeDuplicatesInCollection(collection:ArrayCollection):Array{
        var dic:Dictionary = new Dictionary();

        for each (var item:MyObject in collection){
            var key: Object =  new Object();
            key.network = item.network;
            key.day  = item.day;
            key.date = item.date;
            key.time =item.time;
            key.cost = item.cost;

            dic[JSON.stringify(key)] = item ;
        }

        return DictionaryUtil.getValues(dic) ;
    }